LearnFrenzy
Sign in Take a free test

Lambda Expressions · Lambda Programs · Question 8

Rate limiter with a mutable lambda in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

Write make_limiter(max, window) returning a mutable lambda that, given a timestamp, returns true if the call is allowed (at most max calls in any window starting at the first call of that window).

Solution
main.cpp
#include <iostream>
#include <vector>

auto make_limiter(int max_calls, int window) {
    return [max_calls, window, start = -1000000, used = 0](int t) mutable {
        if (t - start >= window) { start = t; used = 0; }     // new window
        if (used < max_calls) { ++used; return true; }
        return false;
    };
}

int main() {
    auto api = make_limiter(3, 10);
    std::vector<int> requests{0, 1, 2, 3, 9, 10, 11, 12, 13, 25};
    for (int t : requests) std::cout << t << (api(t) ? "+ " : "- ");
    std::cout << '\n';
    auto login = make_limiter(1, 5);
    std::cout << login(0) << login(4) << login(5) << '\n';
    return 0;
}

Output Verified by compiling and running

0+ 1+ 2+ 3- 9- 10+ 11+ 12+ 13- 25+ 
101

The limiter's state (window start and calls used) lives inside the mutable closure, so each limiter is independent – no class needed.

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