Build a calculator that stores operations (+, -, *, /, %, ^) as lambdas in a std::map<char, std::function<double(double, double)>> and evaluates a list of expressions, reporting unknown operators.
Solution
main.cpp
#include <cmath>
#include <functional>
#include <iostream>
#include <map>
int main() {
std::map<char, std::function<double(double, double)>> ops{
{'+', [](double a, double b) { return a + b; }},
{'-', [](double a, double b) { return a - b; }},
{'*', [](double a, double b) { return a * b; }},
{'/', [](double a, double b) { return b == 0 ? NAN : a / b; }},
{'%', [](double a, double b) { return std::fmod(a, b); }},
{'^', [](double a, double b) { return std::pow(a, b); }},
};
struct Expr { double a; char op; double b; } exprs[] = {{12, '+', 30}, {7, '/', 2}, {2, '^', 10}, {17, '%', 5}, {5, '?', 1}, {1, '/', 0}};
for (const auto& e : exprs) {
std::cout << e.a << ' ' << e.op << ' ' << e.b << " = ";
if (auto it = ops.find(e.op); it != ops.end()) std::cout << it->second(e.a, e.b) << '\n';
else std::cout << "unknown operator\n";
}
return 0;
}
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!