gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:10:33 25 4
gpt4 key购买 nike

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

命令是什么?

谢谢。 :)

天空

编辑:

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

也许是一些代码:

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com