我只想检查迭代器是否指向列表中的对象。
命令是什么?
谢谢。 :)
天空
编辑:
嗯,..好的,我试过了。 现在有一个错误:“表达式:列表迭代器不兼容”
也许是一些代码:
#include <list>
list<obj> list;
list<obj>::iterator it;
if(it != list.end()){ //here the error pops up when i debug
vShowStatus();
}else{
cout << "...";
}
最佳答案
你不能。没有办法检查它。您必须构建代码,使迭代器位于 list.begin() 和 list.end() 之间。
这样使用迭代器:
for (std::list<int>::const_iterator it = myList.begin(); it != myList.end(); ++it)
cout << *it << " ";
您无法将 [EDIT] 列表迭代器与关系运算符(<、>、<=、>=)进行比较,因此当您在 for 循环之外使用迭代器时,您必须始终通过与 begin()(如果使用 --it 向后)或 end()(如果使用++it 向前)进行比较,检查您是否越界。
std::list<int>::const_iterator it = ... // initialized with some CORRECT value
// going backward
while (true)
{
cout << *it;
if (it == list.begin())
break;
--it;
}
// going forward
while (true)
{
cout << *it;
++it;
if (it == list.end())
break;
}
// or simplier
while (it != list.end())
{
cout << *it;
++it;
}
如果出于某种原因,您确实需要检查,那么您可以遍历列表并检查是否有任何迭代器与您的迭代器相等。但这可能会对性能产生相当大的影响,因此仅在调试或/和测试中使用它。
关于c++ - 检查迭代器是否引用列表中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2362454/