LearnFrenzy
Sign in Take a free test

Lambda Expressions · Lambda Programs · Question 1

Calculator using a map of lambdas in C++ Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

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;
}

Output Verified by compiling and running

12 + 30 = 42
7 / 2 = 3.5
2 ^ 10 = 1024
17 % 5 = 2
5 ? 1 = unknown operator
1 / 0 = nan

The map replaces a long switch: adding an operator is one line. find() avoids inserting an empty std::function for unknown operators.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links