std::function Callbacks
Completed
Build a map<string, function<long long(long long, long long)>> for add, sub, mul, pow. Read op a b lines and print results or unknown.
Input
n, then n lines.
Output
n lines.
Example
Input
5 add 2 3 mul 4 5 pow 2 10 sub 1 9 mod 7 2
Output
5 20 1024 -8 unknown
Editor
C++
Hints
std::function can hold any callable with the right signature.
Solution explanation
A dispatch table of functions replaces a long if/else chain.
Show solution
#include <iostream>
#include <functional>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, function<long long(long long, long long)>> ops = {
{"add", [](long long a, long long b) { return a + b; }},
{"sub", [](long long a, long long b) { return a - b; }},
{"mul", [](long long a, long long b) { return a * b; }},
{"pow", [](long long a, long long b) {
long long r = 1;
for (long long i = 0; i < b; i++) r *= a;
return r;
}},
};
int n;
cin >> n;
for (int i = 0; i < n; i++) {
string op;
long long a, b;
cin >> op >> a >> b;
auto it = ops.find(op);
if (it == ops.end()) cout << "unknown\n";
else cout << it->second(a, b) << "\n";
}
return 0;
}