泛型算法(二)之测试序列的性质的算法
1、all_of(InputIterator first, InputIterator last, UnaryPredicate pred) : C11算法。如果序列所有元素均满足谓词pred,则返回true
比如,判断一个序列中的元素是不是都小于0:
std::vector<int> c; //添加元素{-10,-9,-8,-7,-6,-5,-4,-3,-2,-1} for (int i = 0; i < 10; i++) { c.push_back(i - 10); } //返回true bool result = std::all_of(c.begin(), c.end(), [](int element){ return element < 0; }); std::cout << (int)result;
//打印结果:1
2、any_of(InputIterator first, InputIterator last, UnaryPredicate pred) : C11算法。如果序列存在元素满足谓词pred,则返回true
std::vector<int> c; //添加元素{-10,-9,-8,-7,-6,-5,-4,-3,-2,-1} for (int i = 0; i < 10; i++) { c.push_back(i - 10); } //因为存在 -10<-9 所以返回true bool result = std::any_of(c.begin(), c.end(), [](int element){ return element < -9; }); std::cout << (int)result;
//打印结果:1
3、none_of(InputIterator first, InputIterator last, UnaryPredicate pred) : C11算法。如果序列中所有元素不满足谓词pred,则返回true
std::vector<int> c; //添加元素{-10,-9,-8,-7,-6,-5,-4,-3,-2,-1} for (int i = 0; i < 10; i++) { c.push_back(i - 10); } //因为不存在大于0的元素,所以返回true bool result = std::none_of(c.begin(), c.end(), [](int element){ return element > 0; }); std::cout << (int)result; //打印结果:1