forked from huangmingchuan/Cpp_Primer_Answers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exercise14_44.cpp
30 lines (25 loc) · 854 Bytes
/
exercise14_44.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string>
#include <map>
#include <functional>
int add(int i, int j) { return i + j; }
auto mod = [](int i, int j) { return i % j; };
struct Div { int operator ()(int i, int j) const { return i / j; } };
auto binops = std::map<std::string, std::function<int(int, int)>>
{
{ "+", add }, // function pointer
{ "-", std::minus<int>() }, // library functor
{ "/", Div() }, // user-defined functor
{ "*", [](int i, int j) { return i*j; } }, // unnamed lambda
{ "%", mod } // named lambda object
};
int main()
{
while (std::cout << "Pls enter as: num operator num :\n", true)
{
int lhs, rhs; std::string op;
std::cin >> lhs >> op >> rhs;
std::cout << binops[op](lhs, rhs) << std::endl;
}
return 0;
}