练习14.33
一个重载的函数调用运算符应该接受几个运算对象?
解答:
这里应该是一个运算对象。
因为“行为像函数”所以有多少个参数都没有问题。
练习14.34
定义一个函数对象类,令其执行if-then-else的操作:该类的调用运算符接受三个形参,它首先检查第一个形参,如果成功返回第二个形参的值;如果不成功返回第三个形参的值。
解答:
#include <iostream>
using namespace std;
class Intcmp{
public:
int operator()(const int& a, const int& b, const int& c) {return (a)? b : c;}
};
int main(){
Intcmp compare;
cout << compare(0, 1, 100) << endl;
cout << compare(8, 1, 100) << endl;
}
练习14.35
编写一个类似于PrintString的类,令其从istream中读取一行输入,然后返回一个表示我们所读内容的string。如果读取失败,返回空string。
解答:
using namespace std;
class Line{
public:
Line(istream &i = cin, char c = ' '):in(i), sep(c){}
string operator()(void) {
string line;
getline(cin, line);
if(line.size()){
return line;
} else{
return "";
}
}
private:
istream ∈
char sep;
};
练习14.36
使用前一个练习定义的类读取标准输入,将每一行保存为vector的一个元素。
解答:
#include <iostream>
#include <vector>
using namespace std;
class Line{
public:
Line(istream &i = cin, char c = ' '):in(i), sep(c){}
string operator()(void) {
string line;
getline(cin, line);
if(line.size()){
return line;
} else{
return "";
}
}
private:
istream ∈
char sep;
};
int main(){
Line line;
string tmp_line;
vector<string> text;
while((tmp_line = line()) != ""){
text.push_back(tmp_line);
}
for(auto i : text){
cout << i << endl;
}
}
练习14.37
编写一个类令其检查两个值是否相等。使用该对象及标准库算法编写程序,令其替换某个序列中具有给定值的所有实例。
解答:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Cmp{
public:
bool operator()(const int &a){
return a == b;
}
static int b;
};
int Cmp::b = 10;
void if_replace(int &a){
Cmp cmp;
if (cmp(a)){
a = 100;
}
}
int main(){
vector<int> test{1,2,1038,49,56,10,35,6,3,4,25,56,3,3,10,4,6,10};
for_each(test.begin(), test.end(), if_replace);
for(auto i : test){
cout << i << endl;
}
}