泛型算法(四)之计数算法
1、count(InputIterator first, InputIterator last, const T& val):序列中等于给定值的元素的计数
std::vector<int> c; c.reserve(10); //向c中添加元素 for (int i = 0; i < 10; i++) { c.push_back(i * 0); } //计算c中元素值等于0的元素个数 int count = std::count(c.begin(), c.end(), 0); //输出 std::cout << count; //打印结果:10
2、count_if(InputIterator first, InputIterator last, UnaryPredicate pred):序列中满足给定谓词的元素的计数
std::vector<int> c; c.reserve(10); //向c中添加元素 for (int i = 0; i < 10; i++) { c.push_back(i); } //计算c中元素值大于5的元素个数 int count = std::count_if(c.begin(), c.end(), [](int element){ return element > 5; }); //输出 std::cout << count; //打印结果:4