Objects of class types that define the call operator are often referred to as function objects that is, they are objects that act like functions.(定义了调用操作符
的类,其对象常称为函数对象
,即它们是行为类似函数
的对象。)
定义BET_cls类,用于测试给定string对象的长度是否与其边界相匹配;
定义GT_cls类,用于测试给定string对象的长度是否在给定值以上;
读入文本文件,使用BET_cls类和GT_cls类,统计长度在1到9之间(含1和9)及10以上的单词的数目(排除相同的单词)。
[1]
使用自己定义的函数对象类
,BET_cls和GT_cls
[2]
改为使用标准库函数对象
代替GT_cls来查找指定长度的单词
[注意]
因为没有可用于直接比较字符串长度的标准库函数对象,所以不能直接使用count_if算法,改用greater_equal对象
循环实现单词计数。
// the following way is right !
wc=0;
greater_equal<string::size_type> grep;// std function object
for (vector<string>::const_iterator iter=words.begin(); iter!=words.end(); ++iter)
{
if (grep(iter->size(), 10))
++wc;
}
cout<<wc<<" "<<make_plural(wc, "word", "s")
<<" 10 characters or longer"<<endl;
return 0;
}
/*
In Anhui province , 560,000 students will take the exams , but only 240,000 will gain places at University .
Competition is fierce ! You must shoulder your parent's expectations ,
the great trust of your school and the hopes of our Motherland !
output:
32 words are of sizes 1 through 9 inclusive
4 words 10 characters or longer
*/