目录

algorithm::all_of()

描述 (Description)

C ++函数std::algorithm::all_of()如果谓词对于从第一个最后一个范围内的所有元素返回true,则返回true。 如果range为空,则返回true,否则返回false。

声明 (Declaration)

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

C++11

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

参数 (Parameters)

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

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

  • pred - 接受元素并返回bool的一元谓词函数。

返回值

如果谓词对范围内的所有元素返回true,或者范围为空,则返回true,否则返回false。

异常 (Exceptions)

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

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

时间复杂

第一个最后一个之间的距离线性。

例子 (Example)

以下示例显示了std :: algorithm :: all_of()函数的用法。

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool is_even(int n) {
   return (n % 2 == 0);
}
int main(void) {
   vector<int> v = {2, 4, 6, 8, 10};
   bool result;
   result = all_of(v.begin(), v.end(), is_even);
   if (result == true)
      cout << "Vector contains all even numbers." << endl;
   v[0] = 1;
   result = all_of(v.begin(), v.end(), is_even);
   if (result == false)
      cout << "Vector doesn't contain all even numbers." << endl;
   return 0;
}

让我们编译并运行上面的程序,这将产生以下结果 -

Vector contains all even numbers.
Vector doesn't contain all even numbers.
↑回到顶部↑
WIKI教程 @2018