Eventually if I am trying to delete all the elements of a vector associated with a key, I am encountering a segmentation fault. My intended output is new b new c new d new a, but i am getting new b new c new d segmentation 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;
}
When you pass an iterator to a container’s erase function, that iterator becomes invalidated. You need to account for that. Assuming, for some reason, that neither
std::removenorstd::remove_ifwill work for your situation, the standard idiom goes like this:When we erase an element, we capture the return value of the erase operation, which is the next iterator. Otherwise, we increment. Note the space where I left room for other possible operations. If there are no other operations, you should be able to just use
std::removeorstd::remove_if, combined with the container’s range erase function (the one that takes two iterators).