1、编写一个类令其检查两个值是否相同,替换掉某个序列中具有给定值的素有实例
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class IntCompare {
public:
IntCompare(int v): val(v) {}
bool operator ()(int v) { return val == v; }
private:
int val;
};
int main()
{
vector<int> vec = { 1,2,3,4,1 };
const int oldValue = 1;
const int newValue = 100;
IntCompare icmp(oldValue);
std::replace_if(vec.begin(), vec.end(), icmp, newValue);
return 0;
}
利用函数对象作为replace_if算法的谓词。
2、编写一个简单的桌面计算器使其能处理二元运算
#include<iostream>
#include<map>
#include<algorithm>
#include<functional>
#include <string>
using namespace std;
map<string,function<int (int, int)>> binOps = {
{"+", plus<int>()},
{"-", minus<int>()},
{"*", multiplies<int>()},
{"/", divides<int>()},
{"%", modulus<int>()}
};
int main()
{
int a, b;
string op;
while (cin >> a >> op >> b) {
cout << to_string(a) << op << to_string(b) << " = ";
cout << binOps[op](a, b) << endl;
}
return 0;
}
运行结果如下