I use std::multimap.lower_bound method to return ranged result. But in the same content of container, sometimes I got the wrong iterators pair and it crash my program. I can see the content in container with visual studio, they are all correct. And I use multimap's find method, it also worked well. It just returns the damned invalid iterators pair and crash my program, and most important of that, I can't do any test to skip that situation. What's wrong with this situation?
My example codes as follows:
std::multimap<std::string,std::string>::iterator it = tagged_files.lower_bound("vocal");
std::multimap<std::string,std::string>::iterator it_end = tagged_files.upper_bound("vocal");
For the most part, they worked well. When I print it
and it_end
with %p(using printf), their results are 8f98ab9(one pointer value) and 0(same key). When I got invalid iterators, debug messages would shows 8f98ab9(same value) and 2b8a839(strange value).
Besides,the size of tagged_files
is always the same. No item was inserted at all during whole session even invalid iterators are received. It also proved by printf %d with tagged_files.size()
.
When I have an invalid iterator with a std container like map, multimaps, 90% of the time, the reason is I am iterating over the container while I am removing items in this container.
As soon as an item is removed (or even insterted in some other containers) in a container, the valid state of iterators is no longer guaranteed.
edit: like the comments below say, rules of invalidation of iterators vary from container to container. cf this question
edit2: you don't show us how you dereference your iterators. Your iterator is a std::pair, and you should check the returned iterator is not equal to yourContainer.end() before you derefence it. But since you don't show us the code where you derefence the iterator it is hard to tell. you don't show us neither the way you output your traces.