Reputation: 3918
When I try to use a set iterator in debug mode in C++, I get an error that says "map/set iterator not dereferencable". I don't understand because I thought dereferincing was how you are supposed to use an iterator. The code looks like this:
set<int>::iterator myIterator;
for(myIterator = mySet.begin();
myIterator != mySet.end();
myIterator++)
DoSomething(*myIterator)
That is the format of all the examples I have seen online about how to use iterators. What am I doing wrong?
Upvotes: 3
Views: 27823
Reputation: 490108
The first and biggest thing you're doing wrong is writing code like this at all. What you have above is the manually-written equivalent of:
std::for_each(mySet.begin(), mySet.end(), DoSomething);
There are relatively few really good uses of iterators outside of implementing algorithms. Once in a while it's reasonable with a map or multimap (or unordered_[multi]map), but that's mostly compensating for map and multimap using std::pair, which isn't entirely wonderful.
Upvotes: 2
Reputation: 3918
This question was based on a false premise. I saw the error "map/set iterator not dereferencable" and thought that that was a general statement that applied to all map/set iterators, which like I said wouldn't make any sense. But I looked again and the real problem was just that the pointer I was using to access that iterator was invalid.
Upvotes: 1
Reputation: 6416
That error generally means you are accessing an "end()" iterator.
Upvotes: 1
Reputation: 78914
If DoSomething()
changes the set - removes or inserts items, then the iterator you're holding is invalidated, which will probably cause this error.
Upvotes: 7