views:

800

answers:

4

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 wrond?

+4  A: 

If DoSomething() changes the set - removes or inserts items, then the iterator you're holding is invalidated, which will probably cause this error.

shoosh
Only slightly true: a `std::set` iterator is invalidated only if the item to which it refers is removed from the set: you can insert any item, and remove any item but one. See 23.1.2/8.
Roger Pate
+2  A: 

That error generally means you are accessing an "end()" iterator.

Sanjaya R
I'm not quite sure how that could be the case here, given the loop's conditions. I might be wrong, though: if I'm wrong, could someone please give me a small example or explanation? Thanks.
Platinum Azure
Platinum: The actual code in the question isn't what he's running, it's just his impression ("looks like").
Roger Pate
A: 

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.

Alex319
+1  A: 

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.

Jerry Coffin
If you're that determined to avoid writing a loop, you can use `unary_compose`, together with a function which maps a pair to its first or second element.
Steve Jessop