multimap<>::equal_range problem

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
Post your code (or a compilable example that reproduces the error, if you can).


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
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++;
}
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.