在 C++ 中使用集合迭代器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1903813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using a Set Iterator in C++
提问by Alex319
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:
当我尝试在 C++ 中的调试模式下使用 set 迭代器时,我收到一条错误消息,指出“map/set iterator not dereferencable”。我不明白,因为我认为取消引用是您应该如何使用迭代器。代码如下所示:
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?
这是我在网上看到的有关如何使用迭代器的所有示例的格式。我究竟做错了什么?
回答by shoosh
If DoSomething()
changes the set - removes or inserts items, then the iterator you're holding is invalidated, which will probably cause this error.
如果DoSomething()
更改集合 - 删除或插入项目,那么您持有的迭代器将失效,这可能会导致此错误。
回答by Jerry Coffin
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.
除了实现算法之外,迭代器的真正好的用途相对较少。偶尔使用 map 或 multimap(或 unordered_[multi]map)是合理的,但这主要是使用 std::pair 来补偿 map 和 multimap,这并不完全是美妙的。
回答by Sanjaya R
That error generally means you are accessing an "end()" iterator.
该错误通常意味着您正在访问“end()”迭代器。
回答by Alex319
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.
这个问题是基于一个错误的前提。我看到错误“map/set iterator not dereferencable”,并认为这是适用于所有 map/set 迭代器的一般声明,就像我说的那样没有任何意义。但是我又看了一遍,真正的问题是我用来访问该迭代器的指针无效。