您的位置:首页 > 编程语言 > Go语言

<algorithm>find函数使用

2016-11-17 20:14 148 查看
  近日,阅读STL源码剖析,其中的find函数与我平时使用的感觉有点差别。于是到c++ reference中去深入了解了一下。

  c++ reference里边是这样写到的template<class InputIterator, class T>
InputIterator find (InputIterator first, InputIterator last, const T& val)
{
while (first!=last) {
if (*first==val) return first;
++first;
}
return last;
}

  其中的返回值是这样描述的:An iterator to the first element in the range that compares equal to
val.If no elements match, the function returns last.大致意思就是返回第一个与所查询值相同的迭代器,如果没找到则返回end迭代器。
  下面是一个例子:#include <iostream>
#include <iterator>
#include <vector>

int main()
{
std::vector<int> my_Vector;

std::istream_iterator<int> startInput(std::cin), endInput; /*定义输入流迭代器*/

//使用输入流迭代器向容器中添加数据
while (startInput != endInput)
my_Vector.push_back(*startInput++);

/*查找容器中的元素*/
std::vector<int>::iterator iter;
iter = std::find(my_Vector.begin(), my_Vector.end(), 12);

if (iter != my_Vector.end())
std::cout << "The number is found:" << *iter << std::endl;
else
std::cout << "The number is not found" << std::endl;
return 0;
}这个例子应该可以帮助一部分人了解一下find函数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐