[英]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". 当我尝试在C ++中以调试模式使用set迭代器时,我收到一个错误,上面写着“map / set iterator not dereferencable”。 I don't understand because I thought dereferincing was how you are supposed to use an iterator.
我不明白,因为我认为dereferincing是你应该如何使用迭代器。 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.
偶尔使用map或multimap(或unordered_ [multi] map)是合理的,但这主要是使用std :: pair来补偿map和multimap,这并不完美。
该错误通常意味着您正在访问“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.
我看到错误“map / set iterator not dereferencable”,并认为这是一个应用于所有map / set迭代器的一般语句,就像我说的那样没有任何意义。 But I looked again and the real problem was just that the pointer I was using to access that iterator was invalid.
但我再看一遍,真正的问题只是我用来访问迭代器的指针无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.