最终,如果我尝试删除与键关联的向量的所有元素,则会遇到分段错误。我的预期输出是新 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;
}