14.36
class CinString {
public:
CinString(istream& is = std::cin):is(is){}
string operator()()const{
string tmp;
if(is >> tmp){
if(!tmp.empty()){
return tmp;
}
}
return "";
}
private:
istream & is;
};
int main(int argc, char *argv[]) {
CinString cs;
string returnString;
vector<string >vs;
while (!(returnString = cs()).empty())
{
cout << returnString << endl;
vs.push_back(returnString);
}
for_each(vs.begin(),vs.end(),[](string& s){ cout << s << endl;});
for (;;);
return 0;
}
14.37
class EqualJudgment {
public:
EqualJudgment(const int & i):theVal(i){}
bool operator()(const int & i){
return i == theVal;
}
private:
int theVal;
};
int main(int argc, char *argv[]) {
vector<int > vc = { 0,1,2,3,4,5,6,7,8,9,1,2,34,5,678,9,8,5,4,1,2,3,6,9 };
replace_if(vc.begin(), vc.end(), EqualJudgment(2), 1000);
for_each(vc.begin(), vc.end(),[](const int & i){ cout << i << endl;});
for (;;);
return 0;
}
14.38
class WordSizeJudgment {
public:
WordSizeJudgment(){}
bool operator()(const string & str, const int theJudgmentSize){
return str.size() == theJudgmentSize;
}
};
int main(int argc, char *argv[]) {
ifstream is("test_2.txt");
string tmpStr;
WordSizeJudgment wsj;
map<int, int>m;
while (is >> tmpStr)
{
for(int size = 1; size <= 10; size++){
if (wsj(tmpStr, size)) {
m[size]++;
}
}
}
for_each(m.begin(),m.end(),[](std::pair<int,int>sd){cout << sd.first << "size str has "<< sd.second << endl;});
for (;;);
return 0;
}
14.39
class WordSizeJudgment {
public:
WordSizeJudgment(){}
bool operator()(const string & str, const int theJudgmentSize){
return str.size() == theJudgmentSize;
}
};
int main(int argc, char *argv[]) {
ifstream is("test_2.txt");
string tmpStr;
WordSizeJudgment wsj;
map<int, int>m;
while (is >> tmpStr)
{
for(int size = 1; size <= 10; size++){
if (wsj(tmpStr, size)) {
m[size]++;
}
}
}
int oneNineCount = 0;
int tenAndUpCount = 0;
for_each(m.begin(),m.end(),[&oneNineCount, &tenAndUpCount](std::pair<int,int>sd){
if(sd.first < 9){
oneNineCount+=sd.second;
}
else{
tenAndUpCount+=sd.second;
}});
cout << "one and nine has" << oneNineCount << endl;
cout << "ten has" << tenAndUpCount << endl;
for (;;);
return 0;
}
14.40
class BiggiesBoth{
public:
bool operator()(const string& a, const string& b){
return a.size() < b.size();
}
};
class BiggiesSize{
public:
BiggiesSize(size_t size):size(size){}
bool operator()(const string& a) {
return a.size() < size;
}
private:
size_t size;
};
class BiggiesPrint{
public:
void operator()(const string& a) {
cout << a << ends;
}
};
void biggies(vector<string >& vecStr, const vector<string>::size_type& sz) {
elimDups(vecStr);
stable_sort(vecStr.begin(), vecStr.end(), BiggiesBoth());
auto wc = find_if(vecStr.begin(),vecStr.end(), BiggiesSize(sz));
auto count = vecStr.end() -wc;
cout << count << " " << "of length" << sz << "or longer " << endl;
for_each(vecStr.begin(),vecStr.end(),BiggiesPrint());
cout << endl;
}
14.41
在某些功能完全不适于其他模块的时候,更没有多个函数需要共享的数据时,使用lambda避免定义不必要的函数对象,简洁程序便于扩展和维护,