如果找不到元素,std :: find会返回什么 [英] What does std::find return if element not found

查看:858
本文介绍了如果找不到元素,std :: find会返回什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据文档, std :: find 返回


last

last

如果未找到任何元素。这意味着什么?它是否返回指向容器中最后一个元素的迭代器?还是返回指向 .end()的迭代器,即指向容器外部的迭代器?
以下代码显示 0 ,它不是容器的元素。因此,我猜 std :: find 返回了容器外部的迭代器。

if no element is found. What does that mean? Does it return an iterator pointing to the last element in the container? Or does it return an iterator pointing to .end(), i.e. pointing outside the container? The following code prints 0, which is not an element of the container. So, I guess std::find returns an iterator outside the container. Could you please confirm?

int main()
{
    vector<int> vec = {1, 2,3, 1000, 4, 5};
    auto itr = std::find(vec.begin(), vec.end(), 456);
    cout << *itr;
}


推荐答案

last 查找的第二个参数的名称。它不知道您使用的是哪种容器,只是您提供给它的迭代器。

last is the name of second parameter to find. It doesn't know what kind of container you're using, just the iterators that you give it.

在您的示例中, last vec.end(),(根据定义)不可取消引用,因为它位于最后一个元素之后。因此,通过取消引用它,可以调用未定义的行为,在这种情况下,该行为表现为打印出0。

In your example, last is vec.end(), which is (by definition) not dereferenceable, since it's one past the last element. So by dereferencing it, you invoke undefined behaviour, which in this case manifests as printing out 0.

这篇关于如果找不到元素,std :: find会返回什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆