C++ Primer(第5版) 练习 14.44
练习 14.44 编写一个简单的桌面计算器使其能处理二元运算。
环境:Linux Ubuntu(云服务器)
工具:vim
代码块
cpp
/*************************************************************************
> File Name: ex14.44.cpp
> Author:
> Mail:
> Created Time: Tue 09 Jul 2024 10:37:09 AM CST
************************************************************************/
#include<iostream>
#include<vector>
#include<functional>
#include<algorithm>
#include<map>
using namespace std;
int add(int a, int b){
return a + b;
}
auto mod = [](int a, int b){ return a % b; };
struct divide{
int operator()(int a, int b){
return a / b;
}
};
int main(){
map<string, function<int(int, int)>> binops = {
{"+", add},
{"-", std::minus<int>()},
{"/", divide()},
{"*", [](int a, int b){ return a * b; }},
{"%", mod}
};
int a, b;
cout<<"Enter a and b: ";
cin>>a>>b;
cout<<"a + b = "<<binops["+"](a, b)<<endl;
cout<<"a - b = "<<binops["-"](a, b)<<endl;
cout<<"a * b = "<<binops["*"](a, b)<<endl;
cout<<"a / b = "<<binops["/"](a, b)<<endl;
cout<<"a % b = "<<binops["%"](a, b)<<endl;
return 0;
}