简体   繁体   中英

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

如果DoSomething()更改了set - 删除或插入项,那么您持有的迭代器将失效,这可能会导致此错误。

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.

该错误通常意味着您正在访问“end()”迭代器。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM