标准库all_of()函数的使用
一、来源与功能
来自<algorithm>头文件,判断容器里的元素是否都满足给定条件
二、使用方式
template <class InputIterator, class UnaryPredicate>
bool all_of (InputIterator first, InputIterator last, UnaryPredicate pred)
三、该函数等价操作实现
template<class InputIterator, class UnaryPredicate>
bool all_of(first != last) {
if (!pred(*first)) return false;
++first;
}
return true;
}
四、参数详解
- first,last
输入迭代器,分别指向第一个元素和最后一个元素下一个位置,区间表示为[first, last)
- pred
谓词,判断区间里的元素是否满足该操作,可以是一个函数指针或者函数对象
五、示例程式
#include<iostream>
#include<array>
#include<algorithm>
int main() {
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 of the elements in the foo are odd numbers" << std::endl;
}
return 0;
}
输出结果
All of the elements in the foo are odd numbers