當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ Algorithm find_if_not()用法及代碼示例


描述

C++ 函數std::algorithm::find_if_not()查找滿足條件的元素的最後一次出現。它用一元謂詞來指定條件。

聲明

以下是 std::algorithm::find_if_not() 函數形式 std::algorithm 頭文件的聲明。

C++11

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

參數

  • first− 將迭代器輸入到初始位置。

  • last− 到最終位置的最終迭代器。

  • pred- 一個一元謂詞,它接受一個參數並返回 bool。

返回值

返回指向範圍內第一個元素的迭代器(第一,最後)為此一元謂詞返回假。如果沒有找到這樣的元素,函數最後返回。

異常

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

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

時間複雜度

線性。

示例

下麵的例子展示了 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.

相關用法


注:本文由純淨天空篩選整理自 C++ Algorithm Library - find_if_not() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。