151. Stateful Lambda Counter

In firmware systems, callbacks often need to maintain their own internal state (for example, counting error pulses, debouncing signals, or tracking retry attempts) without relying on global variables. Using static variables inside functions makes such logic hard to reset, reuse, or test. A stateful lambda provides a clean and encapsulated solution.

Your task is to implement a class Ticker that stores a std::function<void()> callback. In main, you must register a lambda expression with this Ticker that:

  • Maintains an internal integer counter starting at 0
  • Uses lambda capture initialization to store the counter
  • Is marked mutable so it can modify its internal state
  • Increments the counter and prints the updated value on each execution

⚠️ Language Requirement:
This problem requires C++14 or later, due to the use of lambda capture initialization ([count = 0]).

Program Flow:

  1. Instantiate the Ticker class
  2. Register a lambda callback that initializes and maintains an internal counter
  3. Read an integer N
  4. Loop N times:
    • Read a string command cmd
    • If cmd is "TICK", invoke the callback using ticker.tick()

Input Format:

  • First line: Integer N (1 ≤ N ≤ 20)
  • Next N lines: A string cmd ("TICK" or any other string)

Input is provided via standard input (stdin).

Output Format:

  • For every "TICK" command, print:

    Count: <new_value> 
  • Each output must be on a new line
  • If there are no "TICK" commands, produce no output

Example:

Input:

3
TICK
WAIT
TICK

Output:

Count: 1 
Count: 2 

Constraints:

  • Must use a mutable lambda
  • Must not use global variables
  • Must not use static variables inside the lambda
  • Must compile with C++14 or later

 

 

 

 

Loading...

Input

3 TICK WAIT TICK

Expected Output

Count: 1 Count: 2