count_if函数所需的头文件:
#include<algorithm>
函数原型:
template<class InputIterator, class Predicate>
typename iterator_traits<InputIterator>::difference_type
count_if(ForwardIterator first,ForwardIterator last,Predicate pred);
作用:
count_if 算法计算中的元素范围 [first, last),返回满足条件的元素的数量。
示例代码:
计算一组输入中有多少个单词的长度大于6。
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
using namespace std;
class GT_cls{
public:
GT_cls(size_t val=0):bound(val){}
bool operator()(const string &s){
return s.size()>=bound;
}
private:
string::size_type bound;
};
int main(){
string word;
vector<string> sevc;
while(cin>>word)
sevc.push_back(word);
cout<<count_if(sevc.begin(),sevc.end(),GT_cls(6))<<endl;
return 0;
}
第17行应使用一个容器来存储输入的单词,起初写的是
int main(){
string word;
int i;
getline(cin,word);
cout<<count_if(word.begin(),word.end(),GT_cls(6))<<endl;
return 0;
}
会报错booloperator()(conststring &s)不接收一个char*类型的数据。
转载于:https://blog.51cto.com/beyond316/1229626