14.44编写一个简单的桌面计算器使其能处理二元运算。
#include<iostream> #include<map> #include<functional> #include<string> using namespace std; int add(int a,int b) { return a+b; } struct divide{ int operator()(int denominator,int divisor) { return denominator/divisor; } }; auto mode=[](int i,int j) { return i%j;}; int main() { int (*pf)(int,int)=add; map<string,function<int(int,int)>> binops; binops.insert({"+",add}); binops.insert({"+",pf}); binops.insert({"-",minus<int>()}); binops.insert({"*",[](int i,int j) {return i*j;}}); binops.insert({"/",divide()}); binops.insert({"%",mode}); cout<<binops["+"](1,3)<<endl; cout<<binops["-"](2,5)<<endl; cout<<binops["*"](1,2)<<endl; cout<<binops["/"](4,2)<<endl; cout<<binops["%"](4,2)<<endl; return 0; }
运行结果:
时间: 2024-11-13 04:33:01