C++ 如何检查 STL 迭代器是否指向任何东西?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/824157/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:28:00  来源:igfitidea点击:

How to check whether STL iterator points at anything?

c++stliterator

提问by James Hopkin

Possible Duplicate:
C++ Best way to check if an iterator is valid

可能的重复:
C++ 检查迭代器是否有效的最佳方法

I want to do something like this:

我想做这样的事情:

std::vector<int>::iterator it;
// /cut/ search for something in vector and point iterator at it. 
if(!it) //check whether found
    do_something(); 

But there is no operator! for iterators. How can I check whether iterator points at anything?

但是没有运营商!对于迭代器。如何检查迭代器是否指向任何内容?

回答by James Hopkin

You can't. The usual idiom is to use the container's end iterator as a 'not found' marker. This is what std::findreturns.

你不能。通常的习惯用法是使用容器的结束迭代器作为“未找到”标记。这就是std::find返回。

std::vector<int>::iterator i = std::find(v.begin(), v.end(), 13);
if (i != v.end())
{
     // ...
}

The only thing you can do with an unassigned iterator is assign a value to it.

对于未分配的迭代器,您唯一可以做的就是为其分配一个值。

回答by aJ.

Though the iterators are considered as general form of pointers, they are not exactly the pointers. The standard defines Past-the-enditerator to indicate the search failure in containers. Hence, it is not recommended to check the iterators for NULL

尽管迭代器被认为是指针的一般形式,但它们并不完全是指针。该标准定义了Past-the-end迭代器来指示容器中的搜索失败。因此,不建议检查迭代器是否为 NULL

Past-the-endvalues are nonsingular and nondereferenceable.

Past-the-end值是非奇异的和不可解引用的。

if(it != aVector.end())  //past-the-end iterator
    do_something();

回答by Xeningem

If you want to use iterator in a loop, the safest way to use it is in this fashion:

如果你想在循环中使用迭代器,最安全的使用方式是这样的:

for (std::vector<int>::iterator it = v.begin(); it != v.end(); ++it)
{
 do_smth();
}

回答by Xeningem

I believe this should generally give you a good test:

我相信这通常应该给你一个很好的测试:

if (iterator._Mycont == &MyContainer)
{
Probably a valid iterator!
}

You could do tests to make sure that the iterator does not equal the end...

您可以进行测试以确保迭代器不等于结束...

iterator != MyContainer.end()

and:

和:

iterator >= MyContainer.begin()