首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

怎么从结构体向量中删除元素

2012-04-05 
如何从结构体向量中删除元素请教各位想从结构体向量H中删除一项del用迭代器如何实现代码片段如下class Tab

如何从结构体向量中删除元素
请教各位想从结构体向量H中删除一项del用迭代器如何实现
代码片段如下
class Tabu
{
  public:
int vertex;
int ci;
int cj;
int tenure;
};
typedef vector<class Tabu> T_List; 

   
T_List H;//H已被赋值

for(int i=0;i<H.size();i++)
{
  if(H[i].tenure==0)
  {
Tabu del;
  del.vertex=H[i].vertex;
del.ci=H[i].ci;
del.cj=H[i].cj;
del.tenure=H[i].tenure;

  T_List::iterator iter=find(H.begin(),H.end(),del);
for(iter=H.begin();iter!=H.end();++iter)
{
if(iter==del)
H.erase(iter);
}
  }
}  
错误为:error C2679: binary '==' : no operator defined which takes a right-hand operand of type

[解决办法]
应该if(iter==del)改成if(*iter==del)你试试。。。

[解决办法]
if(iter==del)
这个当然不对了,iter返回的是del在H中的位置,del是个类,这两个怎么可以相等
给你贴一段MSDN中find的例子

C/C++ code
// alg_find.cpp// compile with: /EHsc #include <list>#include <algorithm>#include <iostream>int main() {   using namespace std;   list <int> L;   list <int>::iterator Iter;   list <int>::iterator result;      L.push_back( 40 );   L.push_back( 20 );   L.push_back( 10 );   L.push_back( 30 );   L.push_back( 10 );   cout << "L = ( " ;   for ( Iter = L.begin( ) ; Iter != L.end( ) ; Iter++ )      cout << *Iter << " ";   cout << ")" << endl;      result = find( L.begin( ), L.end( ), 10 );   if  ( result == L.end( ) )      cout << "There is no 10 in list L.";   else {      cout << "There is a 10 in list L";      if ( ++result != L.end() )         cout << " and it is followed by a " << *result << ".";   }   cout << endl;}
[解决办法]
必须给 class Tabu 定义一个 operator==() 操作符
[解决办法]
del是一个类的对象,而iter是一个指向该结点的指针。所以修改如下:
for(iter=H.begin(); iter!=H.end(); ++iter)
{
if(iter==&del)
H.erase(iter);
}
[解决办法]
改成上面的代码后,虽然能通过编译,但是因为"iter==&del"比较的是地址,而del是一个栈内的局部变量,这两个应该永远不可能相等(你只要复制了要删除的结点的值而已)。所以即使for循环执行完,也不可能删除你要的结点。

所以你的代码是有问题的。

热点排行