-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
ex14_44.cpp
57 lines (49 loc) · 1.4 KB
/
ex14_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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/***************************************************************************
* @file main.cpp
* @author Alan.W
* @date 21 Jan 2014
* @remark This code is for the exercises from C++ Primer 5th Edition
* @note
***************************************************************************/
//!
//! Exercise 14.44:
//! Write your own version of a simple desk calculator that can handle binary
//! operations.
//!
#include <iostream>
#include <string>
#include <map>
#include <functional>
//! normal function
int add(int i, int j)
{
return i + j;
}
//! named lambda
auto mod = [](int i, int j) { return i % j; };
//! functor
struct wy_div {
int operator()(int denominator, int divisor)
{
return denominator / divisor;
}
};
//! the map
std::map<std::string, std::function<int(int, int)>> binops = {
{"+", add}, // function pointer
{"-", std::minus<int>()}, // library functor
{"/", wy_div()}, // user-defined functor
{"*", [](int i, int j) { return i * j; }}, // unnamed lambda
{"%", mod} // named lambda object
};
int main()
{
while (true) {
std::cout << "\npleasr enter: num operator num :\n";
int n1, n2;
std::string s;
std::cin >> n1 >> s >> n2;
std::cout << binops[s](n1, n2);
}
return 0;
}