#include "D:\C++WORK\main.h"//使用函数对象的函数适配器。
int main()
{
const int ARR_SIZE = 7;
int ia[ARR_SIZE] = {1,1025,2,1026,1030,3,1048};
vector<int> ivec(ia,ia+7);
string sa[ARR_SIZE] = {"many","mach","that","pooh","this","pooh","happy"};
vector<string> svec(sa,sa+ARR_SIZE);
//(a)查找大于1024的所有的数值。
cout<<"所有大于1024的数值"<<endl;
vector<int>::iterator iter = ivec.begin();
while((iter=find_if(iter,ivec.end(),bind2nd(greater_equal<int>(),1024)))!=ivec.end())
{
cout<<*iter<<" ";
++iter;
}
cout<<endl;
//(b)查找所有不等于“pooh”。
vector<string>::iterator iters=svec.begin();
while((iters=find_if(iters,svec.end(),not1(not1(bind2nd(not_equal_to<string>(),"pooh")))))!=svec.end())
{
cout<<*iters<<" ";
++iters;
}
cout<<endl;
//(c)将所有的数值都乘以2
//transform函数的作用是:将某操作应用于指定范围的每个元素
transform(ivec.begin(),ivec.end(),ivec.begin(),bind2nd(multiplies<int>(),2));
cout<<"输出处理后的所有的元素:"<<endl;
iter=ivec.begin();
for (;iter!=ivec.end();++iter)
{
cout<<*iter<<" ";
}
return 0;
}
#include "D:\C++WORK\main.h"//使用标准库函数对象来统计文件中,单词个数大于10的单词的个数
//用于单词的比较的函数
bool isShorter(const string &s1,const string &s2)
{
return s1.size()>s2.size();
}
//如果ctr不为1,返回word的复数的形式
string make_plural(size_t ctr,const string &word,const string &ending)
{
return (ctr==1)?word:word+ending;
}
int main(int argc,char * argv[])
{
//检查命令行参数
if(argc<2)
{
cerr<<"您的输入有错误!"<<endl;
return EXIT_FAILURE;
}
ifstream inFile;
inFile.open(argv[1]);
if (!inFile)
{
cerr<<"无法打开指定的文件"<<endl;
return EXIT_FAILURE;
}
vector<string> words;
string word;
//读入要分析文件中的单词序列
while (inFile>>word)
{
words.push_back(word);
}
//对输入排序一边去掉重复的单词
sort(words.begin(),words.end());
//
words.erase(unique(words.begin(),words.end()),words.end());
//
vector<string>::size_type wc = 0;
greater_equal<string::size_type> grep;//函数类 函数对象
for (vector<string>::iterator iter=words.begin();iter!=words.end();++iter)
{
if (grep(iter->size(),10))/*调用函数对象*/
{
++wc;
}
}
cout<<"长度大于10的单词的个数是:"<<" "<<wc<<make_plural(wc,"word","s")<<endl;
return 0;
}