开发者

Using a Set Iterator in C++

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.beg开发者_StackOverflow中文版in();
    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?


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


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜