在c++中从列表中删除项

Removing item from list in c++

本文关键字:删除 列表 c++      更新时间:2023-10-16

大家好,我正在为哈希表编写代码,我想在列表中删除一些字符串值的删除函数。

void Hash::remove(string word)
{
  int i,flag=0;
  list<string>::iterator it;
  for(i=0;i<10;i++)
  {
   for(it=hashTable[i].begin();it!=hashTable[i].end();it++)
   {
   if(word==*it){
   hashTable.erase(it);
   break;
   }
  }
 }
}

但是当我编译得到一个错误:错误:请求成员' erase '在' ((Hash*)this)->Hash::hashTable '中,它是非类类型' std::list> [10] '

我不能理解这个。

hashTable[i].erase(it)代替hashTable.erase(it)

从您的描述中,似乎您要删除与word匹配的所有元素。不确定为什么要使用两个循环和一个break语句。你可以使用Erase - Remove习语来有效地从容器中删除元素。

在c++ 11中,你可以尝试-

hashTable.erase( std::remove( std::begin(hashTable), 
                              std::end(hashTable),
                              [word](const std::string& str){ return str == word;} ), 
                              std::end(hashTable) );