Home C&C++函数库 c++ 语法 程序源码 Linux C库

std::

find

函数模板  <algorithm>
template <class InputIterator, class T>
   InputIterator find (InputIterator first, InputIterator last, const T& val);

在范围内查找值

返回一个迭代器,指向范围[first,last]中与val相等的第一个元素。 如果没有找到这样的元素,函数返回last。
该函数使用operator==将单个元素与val进行比较。

这个函数模板的行为相当于:
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;
}

☲  参数


first, last
指向序列初始和最终位置的输入迭代器。使用的范围是[first,last], 它包含first和last之间的所有元素,包括first指向的元素,但不包括last指向的元素。
val
要在范围内搜索的值。
T应该是一种类型,支持与InputIterator使用operator==(将元素作为左侧操作数, val作为右侧操作数)所指向的元素进行比较。

☉  返回值



指向范围内值等于val的第一个元素的迭代器。
如果没有匹配的元素,函数返回last。

☣  示例



// find example
#include <iostream>     // std::cout
#include <algorithm>    // std::find
#include <vector>       // std::vector

int main () {
  // using std::find with array and pointer:
  int myints[] = { 10, 20, 30, 40 };
  int * p;

  p = std::find (myints, myints+4, 30);
  if (p != myints+4)
    std::cout << "Element found in myints: " << *p << '\n';
  else
    std::cout << "Element not found in myints\n";

  // using std::find with vector and iterator:
  std::vector<int> myvector (myints,myints+4);
  std::vector<int>::iterator it;

  it = find (myvector.begin(), myvector.end(), 30);
  if (it != myvector.end())
    std::cout << "Element found in myvector: " << *it << '\n';
  else
    std::cout << "Element not found in myvector\n";

  return 0;
}

输出:
Element found in myints: 30
Element found in myvector: 30

✥ 复杂度



在first 和last之间的distance达到线性:比较元素,直到找到匹配。

⇄ 数据竞争


[first,last)范围内的部分(或全部)对象被访问(最多一次)。

☂ 异常安全性



如果元素比较或迭代器上的操作抛出,则抛出。
注意,无效的参数会导致未定义的行为。

🍄  另请参阅



search 搜索子序列的范围(函数模板)
binary_search 测试value是否存在于排序序列中(函数模板)
for_each 将函数应用于范围(函数模板)

联系我们 免责声明 关于CandCplus 网站地图