function template
<algorithm>

std::find

template <class InputIterator, class T>   InputIterator find (InputIterator first, InputIterator last, const T& val);
在範圍內查詢值
返回一個迭代器,指向範圍 [first,last) 中第一個與 val 相等的元素。如果未找到此類元素,則函式返回 last

該函式使用 operator== 將單個元素與 val 進行比較。

此函式模板的行為等同於
1
2
3
4
5
6
7
8
9
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),它包含 firstlast 之間的所有元素,包括 first 指向的元素,但不包括 last 指向的元素。
val
要在範圍內查詢的值。
T 應為支援透過 operator==InputIterator 指向的元素(元素作為左側運算元,val 作為右側運算元)與 val 進行比較的型別。

返回值

指向範圍中第一個與 val 相等的元素的迭代器。
如果沒有元素匹配,則函式返回 last

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// 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


複雜度

線性於 firstlast 之間的 距離:比較元素直到找到匹配項。

資料競爭

範圍 [first,last) 中的一些(或全部)物件被訪問(最多一次)。

異常

如果元素比較或迭代器操作引發異常,則丟擲。
請注意,無效引數會導致未定義行為

另見