c++ - 检查迭代器是否引用列表中的项目

标签 c++ list iterator

我只想检查迭代器是否指向列表中的对象。

命令是什么?

谢谢。 :)

天空

编辑:

嗯,..好的,我试过了。 现在有一个错误:“表达式:列表迭代器不兼容”

也许是一些代码:

#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/

相关文章:

python groupby行为?

c++ - QsortFilterProxyModel 删除多列

C++ 命名空间规范是多余的还是有用的?

c++ - 将特定格式的字符串拆分为 float 和字符串

list - 在Scheme中仅使用CONS命令写入列表

python - 如何读取文件的第一行两次?

c++ - 错误 : identifier "img" is undefined

android - 带有自定义数据源的分页库在房间更新时不更新行

python - Python:如何在列表中添加单词?

C++:为常量迭代器重载 list.end() 和 list.begin() 方法