14.34 define a function object class to execute the if-then-else operation. The call operator of this type accepts three parameters. It first checks the first parameter, if the result is successful, the value of the second parameter is returned. If the result is unsuccessful, the value of the third parameter is returned.
#include<iostream>using namespace std;class if_then_else{public: int operator()(int a,int b,int c) const { if(a) return b; else return c; }};int main(){ if_then_else f; cout<<f(3,4,5)<<endl; return 0;}
14.35 write a printstring class to read a row of input from istream, and return a string representing the content we read. If the read fails, a null string is returned.
#include<iostream>#include<string>#include<vector>using namespace std;class PrintString{public: PrintString(ostream &o=cout,char c=‘ ‘):os(o),sep(c) {} void operator()(const string &s) { os<<s<<sep;}private: ostream &os; char sep;};int main(){ string str; PrintString p; if(getline(cin,str)) p(str); else p(string()); return 0;}
14.36 read the standard input using the class defined above and save each row as an element of the vector.
# Include <iostream> # include <string> # include <vector> using namespace STD; Class printstring {public: printstring (ostream & O = cout, istream & I = Cin, char c = ''): OS (O), is (I), SEP (c) {} void operator () (const string & S) {OS <S <Sep;} istream & operator () (string & S) {Getline (is, S); return is;} PRIVATE: ostream & OS; istream & is; char Sep ;}; int main () {vector <string> VEC; string STR; printstring P; while (P (STR) // input Vec. push_back (STR); For (const Auto V: VEC)
P (V); // output/* If (Getline (CIN, STR) P (STR); else P (string (); */return 0 ;}
14.37 write a class to check whether two values are equal. Use this object and the standard library algorithm to write a program, so that it replaces all instances with a given value in a sequence.
#include<iostream>#include<string>#include<vector>#include<algorithm>using namespace std;class replaces{public: replaces(string s1="old",string s2="new"):oldval(s1),newval(s2) {} void operator()(string &s){ if(s==oldval) s=newval;}private: string oldval; string newval;};int main(){ vector<string> vec={"old","a","old","b","old"}; for_each(vec.begin(),vec.end(),replaces()); for(auto v:vec) cout<<v<<" "; cout<<endl; return 0;}
Function call Operators