STL all_of函数

STL all_of函数算法

STL 的 algorithm 头文件中定义了 3 种算法,用来检查在算法应用到序列中的元素上时,什么时候使谓词返回 true。all_of() 算法会返回 true,前提是序列中的所有元素都可以使谓词返回 true。

STL all_of函数详解

头文件

#include <algorithm>

语法

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

参数

参数 描述
first 输入迭代器
last 输入迭代器
pred 自定义比较规则

说明

first, last 标示序列范围的输入迭代器。包括 first 指向的元素,但不包括 last。

pred 一个接受一个元素类型参数并返回一个 bool 值的一元函数。可以是一个指针或者函数对象。

技术细节

如果对于范围 [first,last)内每个元素,一元断言都为真,或者范围为空,那么返回 true,否则返回 false。

案例

STL all_of函数

使用 STL all_of 函数判断集合

#include <iostream> #include <algorithm> using namespace std; bool isGreatOne(int i) { if(i>=1) { return true; } else { return false; } } int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; vector<int> vi{0,1,2,3,4,5,6}; if(all_of(vi.begin(),vi.end(), isGreatOne)) { cout<<"Yes,all elements in vi >1 "<<endl; } else { cout<<"no,some of elements in vi didn't >=1 "<<endl; } cout<<endl; int ar[5]={10,20,30,40,50}; if(all_of(ar,ar+5,[](int i){return i%10;})) { cout<<"all in ar can %10!=0"<<endl; } else { cout<<"some %10=0!"<<endl; } }

我们在 Linux 下使用 g++ 进行编译,具体命令如下:

g++ all_of.cpp -std=c++11

编译后,我们直接运行生成的二进制文件 a.out,如下图所示:

26_STL all_of函数.png

all_of 函数会判断所有的元素都符合要求,才会返回 true。

STL all_of函数

使用 STL all_of 函数判断集合

#include <iostream> #include <algorithm> using namespace std; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; std::array<int,8> foo = {3, 5, 7, 11, 13, 17, 19, 23}; if ( std::all_of(foo.begin(), foo.end(), [](int i){return i%2;}) ) { std::cout << "All the elements are odd numbers.\n"; } }

我们在 Linux 下使用 g++ 进行编译,具体命令如下:

g++ all_of.cpp -std=c++11

编译后,我们直接运行生成的二进制文件 a.out,如下图所示:

27_STL all_of函数.png

all_of 函数会判断所有的元素都符合要求,才会返回 true。

STL all_of函数总结

在 STL 的 algorithm 头文件中定义了 3 种算法,用来检查在算法应用到序列中的元素上时,什么时候使谓词返回 true。all_of() 算法会返回 true,前提是序列中的所有元素都可以使谓词返回 true。