multimap<>::equal_range problem

Apr 3, 2011 at 1:53am
I'm trying to use the method shown here:
http://www.cplusplus.com/reference/stl/multimap/equal_range/

to find and remove a particular key,value pair.

however, when i get to the call to increment the iterator, i get a debug assertion telling me that multimap iterators are not incrementable, though clearly in this example it shows it to be
Apr 3, 2011 at 7:23am
Post your code (or a compilable example that reproduces the error, if you can).
Apr 3, 2011 at 3:32pm


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
std::pair<std::multimap<InputFun,SDLKey>::iterator,std::multimap<InputFun,SDLKey>::iterator> lfkret;
std::pair<std::multimap<SDLKey,InputFun>::iterator,std::multimap<SDLKey,InputFun>::iterator> lkfret;

lfkret = ainput.mFunKey.equal_range( afun );
for( std::multimap<InputFun,SDLKey>::iterator it = lfkret.first;
		it != lfkret.second;
		++it ){

	lkfret = ainput.mKeyFun.equal_range( it->second );
		
	for( std::multimap<SDLKey,InputFun>::iterator it2 = lkfret.first;
			it2 != lkfret.second;
			++it2 ){
		if( it2->second==afun ){
			ainput.mKeyFun.erase( it2 );
		}
	}

	ainput.mFunKey.erase( it );
}


Debug assertion fails when it gets to ++it2 :
"Expression: map/set iterator not incrementable"
Last edited on Apr 3, 2011 at 4:13pm
Apr 3, 2011 at 6:08pm
That's because you erase while iterating. Due to that, it2 may point to end() and when you increment end() iterator, you get that error.
If I recall correctly, the solution is
1
2
3
4
for(something::iterator it = begin; it != end; ){
   if(condition) it = container.erase(it);
   else it++;
}
Apr 4, 2011 at 3:35am
Thanks hamsterman my next guess would have been that.

In my example what if there are more than 1 entry in the map with the same key,value pair?

When I erase, supposedly it gets set to end().

Should I make a list of iterators that need erasing and then just traverse and erase from the saved list of iterators?
Topic archived. No new replies allowed.