最终,如果我试图删除与键关联的向量的所有元素,我遇到了分段错误。我的预期输出是新的b new c new d new a,但是我得到了新的b new c new d segment fault。
#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;
}
答案 0 :(得分: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::remove
或std::remove_if
,并结合容器的范围擦除功能(带两个迭代器的功能)。