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



描述

C++ 函式 std::algorithm::any_of() 返回 true,如果謂詞對於範圍內的任何元素返回 true起始結束。如果範圍為空,則也返回 true,否則返回 false。

宣告

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

C++11

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

引數

  • first − 輸入迭代器指向序列中的起始位置。

  • last − 輸入迭代器指向序列中的結束位置。

  • pred − 一個一元謂詞函式,接受一個元素並返回一個bool.

返回值

如果謂詞對範圍內的任何元素返回 true,或者範圍為空,則返回 true;否則返回 false。

異常

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

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

時間複雜度

線性於…之間的距離起始結束.

示例

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

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

using namespace std;

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

int main(void) {
   vector<int> v = {2, 4, 6, 8, 11};
   bool result;

   result = any_of(v.begin(), v.end(), is_odd);

   if (result == true)
      cout << "Vector contains at least one odd number." << endl;

   v[4] = 10;

   result = any_of(v.begin(), v.end(), is_odd);

   if (result == false)
      cout << "Vector contains all even number." << endl;

   return 0;
}

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

Vector contains at least one odd number.
Vector contains all even number.
algorithm.htm
廣告