1、編寫(xiě)一個(gè)類(lèi)令其檢查兩個(gè)值是否相同,替換掉某個(gè)序列中具有給定值的素有實(shí)例
#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;
}
利用函數(shù)對(duì)象作為replace_if算法的謂詞。
2构诚、編寫(xiě)一個(gè)簡(jiǎn)單的桌面計(jì)算器使其能處理二元運(yùn)算
#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;
}
運(yùn)行結(jié)果如下
image.png