函式模板
<algorithm>

std::find_if

template <class InputIterator, class UnaryPredicate>   InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred);
在範圍內查詢元素
返回一個迭代器,指向範圍 [first,last) 中第一個使 pred 返回 true 的元素。如果找不到這樣的元素,則函式返回 last

此函式模板的行為等同於
1
2
3
4
5
6
7
8
9
template<class InputIterator, class UnaryPredicate>
  InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred)
{
  while (first!=last) {
    if (pred(*first)) return first;
    ++first;
  }
  return last;
}

引數

first, last
輸入迭代器 指向序列的起始和結束位置。使用的範圍是 [first,last),它包含 firstlast 之間的所有元素,包括 first 指向的元素,但不包括 last 指向的元素。
pred
一元函式,接受範圍中的元素作為引數,並返回可轉換為 bool 的值。返回值指示該元素是否在函式上下文中被視為匹配項。
該函式不得修改其引數。
這可以是函式指標或函式物件。

返回值

指向範圍中第一個使 pred 返回 false 的元素的迭代器。
如果 pred 對所有元素都返回 false,則函式返回 last

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// find_if example
#include <iostream>     // std::cout
#include <algorithm>    // std::find_if
#include <vector>       // std::vector

bool IsOdd (int i) {
  return ((i%2)==1);
}

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

  myvector.push_back(10);
  myvector.push_back(25);
  myvector.push_back(40);
  myvector.push_back(55);

  std::vector<int>::iterator it = std::find_if (myvector.begin(), myvector.end(), IsOdd);
  std::cout << "The first odd value is " << *it << '\n';

  return 0;
}

輸出
The first odd value is 25


複雜度

最多與 firstlast 之間的 距離 成線性關係:對每個元素呼叫 pred 直到找到匹配項。

資料競爭

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

異常

如果 pred 或迭代器上的操作丟擲異常,則丟擲異常。
請注意,無效的引數會導致 *未定義行為*。

另見