了解查找和向量 C++

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

Understanding find and vectors C++

c++vectorfind

提问by Jake Smith

I'm trying to understand this line of code

我试图理解这行代码

vector<int>::iterator it = find(list_vector.begin(), list_vector.end(), 5)

where I have vector<int> list_vector;declared before hand.

vector<int> list_vector;事先声明的地方。

What does the 5 do? What does it return? Does it return the 5 if it can find it at the beginning and end? If I wanted to make an if statement, and I wanted to find if the number 10 was in the statement (if it was, return true) how would I go about doing that?

5是做什么的?它返回什么?如果它可以在开头和结尾找到它,它会返回 5 吗?如果我想做一个 if 语句,并且我想找出该语句中是否有数字 10(如果是,则返回 true),我该怎么做?

回答by Rob?

vector<int>::iterator it = find(list_vector.begin(), list_vector.end(), 5)

std::findsearches in the range defined by its first two arguments. It returns an iterator pointing to the first element that matches. If no element matches, it returns its 2nd parameter.

std::find在由其前两个参数定义的范围内搜索。它返回一个指向第一个匹配元素的迭代器。如果没有元素匹配,它返回它的第二个参数。

list_vector.begin()returns an iterator that points to the first element of list_vector.

list_vector.begin()返回一个指向第一个元素的迭代器list_vector

list_vector.end()returns an iterator that points one element beyond the final element of list_vector.

list_vector.end()返回一个迭代器,该迭代器指向 的最后一个元素之外的一个元素list_vector

5is the target of the search. find()will look for an element that has the value 5.

5是搜索的目标。find()将查找具有 value 的元素5

If you'd like to determine if 10 is present anywhere in the vector, do this:

如果您想确定向量中的任何位置是否存在 10,请执行以下操作:

if(std::find(list_vector.begin(), list_vector.end(), 10) == list_vector.end())
    std::cout << "No 10, bummer\n";
else
    std::cout << "I found a 10!\n";

Or, if you'd like to simultaneously determine if 10 is present anddetermine its location:

或者,如果您想同时确定 10 是否存在确定其位置:

std::vector<int>::iterator it = std::find(list_vector.begin(), list_vector.end(), 10);
if(it == list_vector.end())
    std::cout << "No 10\n";
else
    std::cout << "Look what I found: " << *it << "\n";