0

最终,如果我尝试删除与键关联的向量的所有元素,则会遇到分段错误。我的预期输出是新 b 新 c 新 d 新 a,但我得到新 b 新 c 新 d 分段错误。

    #include <iostream>
#include <vector>
#include <map>
#include <algorithm>

using namespace std;

int main ()
{
  map<char,vector<char> > mmap; //multimap 
  char mychar[] = { 'b','c', 'd'};
  vector<char> vec (mychar,mychar+3);
  vector<char> newvec; 

  mmap.insert (pair<char,vector<char> >('a',vec)); //insert to multimap
  mmap.insert (pair<char,vector<char> >('b',vector<char>()));
  mmap.insert (pair<char,vector<char> >('c',vector<char>()));
  mmap.insert (pair<char,vector<char> >('d',vector<char>()));

  vector<char>::iterator veciter; 
  map<char,vector<char> >::iterator mapiter;

  for(int i=0;i<6;i++)
  {  
  for ( mapiter = mmap.begin(); mapiter != mmap.end(); ++mapiter) 
  {
    //if elements associated with vector of a key are empty the store the key in a new vector
    if(mapiter->second.empty()) 
    {
      newvec.push_back (mapiter->first);
      mmap.erase(mapiter);
    }
    else
    {
       for (veciter = mapiter->second.begin(); veciter != mapiter->second.end(); ++veciter)
       {
         //if an element of a vector of key is found in new vector, erase the element
         if (find(newvec.begin(), newvec.end(), *veciter)!=newvec.end())   
         {
            mapiter->second.erase(veciter);
         }

       }
    }
    // to display values of new vector     
    for (unsigned i=0; i<newvec.size(); ++i)
    cout << "new " << newvec[i]<<' ';
    cout << '\n'; 
  }  
  }

  return 0;
}
4

1 回答 1

3

当您将迭代器传递给容器的擦除函数时,该迭代器将失效。你需要考虑到这一点。假设,由于某种原因,既不std::remove也不std::remove_if适合你的情况,标准的成语是这样的:

for (it = container.begin(); it != container.end(); /* no increment here */)
{
    if (should_be_removed(*it))
    {
        // possibly other operations involving the element we are about to remove
        it = container.erase(it);
    }
    else
    {
        // possibly other operations involving the element we chose not to remove
        ++it;
    }
}

当我们擦除一个元素时,我们会捕获擦除操作的返回值,即下一个迭代器。否则,我们增加。请注意我为其他可能的操作留出空间的地方。如果没有其他操作,您应该可以只使用std::removeor std::remove_if,并结合容器的范围擦除功能(需要两个迭代器的功能)。

于 2012-12-08T19:26:13.180 回答