0

I am using a std::multimap

std::multimap<string,string> map;

It contains elements below

1 2  
2 3
3 2
1 2
1 0

I want to replace all 1's and 2's by X. I searched in google for a long time, but didn't get the result. I tried like

for(it=mmap.begin();it!=mmap.end();it++)
{
   if(it->first == "1" || it->first == "2")
   {
     key = it->second;
     it.erase(it);
     mmap.insert(pair<string,string>("X",key));
   }
}

but ended up in wrong result . I understand the size varies each time and when we insert the element gets inserted at the end which in turn ends the for loop. any other way to come out of this?

LihO
  • 41,190
  • 11
  • 99
  • 167
  • That code won't compile. – Alex Chamberlain Feb 25 '13 at 13:22
  • See [`std::multimap::lower_bound()`](http://en.cppreference.com/w/cpp/container/map/lower_bound) and the linked reference within that to `std::multimap::upper_bound()`. They will get the ranges you're looking for, though I question your desire to mod-the-map while enumerating it like this. – WhozCraig Feb 25 '13 at 15:36

2 Answers2

0

You are modifying container while iterating it, it is bad.

I suggest you to store all values you want to replace, remove them, and place everything you want back.

Or just create new map with desired values

kassak
  • 3,974
  • 1
  • 25
  • 36
0

I understand the size varies each time and when we insert the element gets inserted at the end

No it doesn't, it inserts a new element in such position as to preserve the ordering.

What you need to do is this.

// for "1"
while (auto I = mmap.lower_bound ("1"), I != mmap.end())
{
    mmap.insert(pair<string,string>("X",I->second));
    mmap.erase (I);
}

// Same for "2"
while (auto I = mmap.lower_bound ("2"), I != mmap.end())
{
    mmap.insert(pair<string,string>("X",I->second));
    mmap.erase (I);
}