Rehrasing the question - Question rephrased - I have a requirement where I need to replace a pair with a new key and value. Consider this -
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
std::multimap<unsigned int, std::string> mymap;
mymap.insert(std::multimap<unsigned int, std::string>::value_type(0, "A1"));
mymap.insert(std::multimap<unsigned int, std::string>::value_type(0, "A2"));
mymap.insert(std::multimap<unsigned int, std::string>::value_type(2, "C1"));
mymap.insert(std::multimap<unsigned int, std::string>::value_type(2, "C2"));
mymap.insert(std::multimap<unsigned int, std::string>::value_type(1, "B1"));
mymap.insert(std::multimap<unsigned int, std::string>::value_type(1, "B2"));
mymap.insert(std::multimap<unsigned int, std::string>::value_type(1, "B3"));
std::pair<std::multimap<unsigned int, std::string>::iterator, std::multimap<unsigned int, std::string>::iterator> pr = mymap.equal_range(1);
std::multimap<unsigned int, std::string>::iterator it;
for (it=pr.first; it!=pr.second; ++it)
{
unsigned int key = it->first;
key = key+10;
std::string val = it->second;
val = "X" + val;
mymap.erase(it);
mymap.insert(std::multimap<unsigned int, std::string>::value_type(key, val));
}
for ( it=mymap.begin() ; it != mymap.end(); it++ )
{
cout << (*it).first << " => " << (*it).second << endl;
}
return 0;
}
The program crashes on visual studio 2008 since the iterator is invalidated.
I expect it to be:
0 => A1
0 => A2
2 => C1
2 => C2
11 => XB1
11 => XB2
11 => XB3
The idea is I want to replace an existing entry in the map with a new entry.
What am I doing wrong? Any help very much appreciated.
The trick is to advance the iterator first, then erase a copy of the iterator.
std::multimap<unsigned int, std::string>::iterator it = pr.first;
while (it != pr.second)
{
unsigned int key = it->first;
key = key+10;
std::string val = it->second;
val = "X" + val;
std::multimap<unsigned int, std::string>::iterator itCopy = it;
++it;
mymap.erase(itCopy);
mymap.insert(std::multimap<unsigned int, std::string>::value_type(key, val));
}
In C++11, you can do this:
std::multimap<unsigned int, std::string>::iterator it = pr.first;
while (it != pr.second)
{
unsigned int key = it->first;
key = key+10;
std::string val = it->second;
val = "X" + val;
it = mymap.erase(it);
mymap.insert(std::multimap<unsigned int, std::string>::value_type(key, val));
}
By the way, because this code is increasing the key each time, it will process every element over and over again.