当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ Algorithm any_of()用法及代码示例



描述

C++ 函数std::algorithm::any_of()返回真如果谓词对范围内的任何元素返回真第一的最后的.如果范围为空,则也返回真,否则返回假。

声明

以下是 std::algorithm::any_of() 函数形式 std::algorithm 头文件的声明。

C++11

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

参数

  • first− 将迭代器输入序列中的初始位置。

  • last− 将迭代器输入到序列中的最终位置。

  • pred- 一个一元谓词函数,它接受一个元素并返回一个布尔

返回值

如果谓词对范围内的任何元素返回真,或者如果范围为空,则返回真,否则返回假。

异常

如果谓词或迭代器上的操作抛出异常,则抛出异常。

请注意无效的参数会导致未定义的行为。

时间复杂度

之间的距离呈线性第一的最后的

示例

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

相关用法


注:本文由纯净天空筛选整理自 C++ Algorithm Library - any_of() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。