C++算法count_if()函数具有'pred'值,并返回pred值为true的[first,last)参数内的元素计数。
template <class InputIterator, class UnaryPredicate> typename iterator_traits<InputIterator>::difference_type count_if(InputIterator first, InputIterator last,UnaryPredicate pred);
first:它是参数中第一个元素的输入迭代器。
last:它是参数中最后一个元素的输入迭代器。
val :这是在参数中搜索其出现的元素。
该函数返回pred值为true的[first,last)参数内的元素数。
链接:https://www.learnfk.comhttps://www.learnfk.com/c++/cpp-algorithm-count-if-function.html
来源:LearnFk无涯教程网
#include<iostream> #include<algorithm> #include<vector> bool isOdd(int k) { return((k%2)==1); } int main() { std::vector<int> newvector; for(int k=1; k<10; k++) newvector.push_back(k); int newcount=count_if(newvector.begin(),newvector.end(),isOdd); std::cout<<"newvector contains "<<newcount<<" odd values.\n"; return 0; }
输出:
newvector contains 5 odd values.
#include<bits/stdc++.h> using namespace std; bool isEven(int k) { if(k%2==0) return true; } int main() { vector<int> u; for(int i=0; i<10; i++) { u.push_back(i); } int noEven=count_if(u.begin(),u.end(),isEven); cout<<"Count of even number is:"<<noEven; return 0; }
输出:
Count of even number is: 10
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)