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



描述

C++ 函式 std::algorithm::find_if_not() 查詢滿足條件的元素的最後一個出現位置。它使用一元謂詞來指定條件。

宣告

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

C++11

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

引數

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

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

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

返回值

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

異常

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

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

時間複雜度

線性。

示例

以下示例演示了 std::algorithm::find_if_not() 函式的使用方法。

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

using namespace std;

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

int main(void) {
   vector<int> v = {2, 4, 61, 8, 10};
   auto it = find_if_not(v.begin(), v.end(), unary_pred);

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

   v = {2, 4, 6, 8, 10};

   it = find_if_not(v.begin(), v.end(), unary_pred);

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

   return 0;
}

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

First odd number is 61
Only enven elements present in the sequence.
algorithm.htm
廣告