C++ 演算法庫 - find_if() 函式



描述

C++ 函式std::algorithm::find_if() 查詢滿足條件的元素的第一次出現。它使用一元謂詞來指定條件。

宣告

以下是來自 std::algorithm 標頭檔案的 std::algorithm::find_if() 函式宣告。

C++98

template <class InputIterator, class UnaryPredicate>
InputIterator find_if (InputIterator first, InputIterator last, 
   UnaryPredicate pred);

引數

  • first − 輸入迭代器指向起始位置。

  • last − 輸入迭代器指向結束位置。

  • pred − 一個一元謂詞,接受一個引數並返回 bool 值。

返回值

返回一個迭代器,指向範圍內的第一個元素(first,last)其中一元謂詞返回 true。如果找不到這樣的元素,則函式返回last.

異常

如果謂詞或迭代器上的操作丟擲異常,則丟擲異常。

請注意,無效引數會導致未定義的行為。

時間複雜度

線性,即 O(n)

示例

以下示例顯示了 std::algorithm::find_if() 函式的用法。

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

bool unary_pre(int n) {
   return ((n % 2) == 0);
}

int main(void) {
   vector<int> v = {10, 2, 3, 4, 5};
   auto it = find_if(v.begin(), v.end(), unary_pre);

   if (it != end(v))
      cout << "First even number is " << *it << endl;

   v = {1};

   it = find_if(v.begin(), v.end(), unary_pre);

   if (it == end(v))
      cout << "Only odd elements present in the sequence." << endl;

   return 0;
}

讓我們編譯並執行上面的程式,這將產生以下結果:

First even number is 10
Only odd elements present in the sequence.
algorithm.htm
廣告