Using Set Iterator in C ++

When I try to use the set iterator in debug mode in C ++, I get the error "map / set iterator not dereferencable". I do not understand, because I thought you should use an iterator. The code is as follows:

set<int>::iterator myIterator;
for(myIterator = mySet.begin();
    myIterator != mySet.end();
    myIterator++)
    DoSomething(*myIterator)

This is the format of all the examples I've seen on the Internet about how to use iterators. What am I doing wrong?

+3
source share
4 answers

If it DoSomething()changes the set - deletes or inserts elements, then the iterator you are holding is invalid, which is likely to cause this error.

+7
source

, , - . , , :

std::for_each(mySet.begin(), mySet.end(), DoSomething);

. multimap ( unordered_ [multi] map), multimap std:: pair, .

+2

, "end()".

+1

This question was based on a false premise. I saw the error "map / set iterator not dereferencable" and thought it was a general statement that applies to all map / set iterators, which, as I said, make no sense. But I looked again, and the real problem was that the pointer I used to access this iterator was invalid.

+1
source

Source: https://habr.com/ru/post/1725666/


All Articles