Skip to content
C++: Keep a rolling total with a deque

C++: Keep a rolling total with a deque

November 12, 2026

A rolling total only needs the current window and its sum. A deque lets the update remove the oldest reading from the front and append a new reading at the back.

Prepare a scratch directory

Tested on Linux with GCC 14.2.0 in C++20 mode. You need Bash, a C++20 compiler and standard library, a text editor, and the mktemp, rm, and rmdir utilities. Keep the same terminal open. Stop if setup fails, before saving the source:

start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1

Run the example

Save as cpp-deque-rolling-window-total.cpp:

#include <cassert>
#include <cstddef>
#include <deque>
#include <iostream>

int main() {
    constexpr std::size_t capacity = 3;
    static_assert(capacity > 0);
    std::deque<int> window;
    long long total = 0;
    for (int reading : {4, 7, 2, 9, 1}) {
        if (window.size() == capacity) {
            total -= window.front();
            window.pop_front();
        }
        window.push_back(reading);
        total += reading;
        assert(window.size() <= capacity);
        std::cout << "count=" << window.size() << " total=" << total << '\n';
    }
    assert((window == std::deque<int>{2, 9, 1}));
    assert(total == 12);
}

Compile and run:

g++ -std=c++20 -Wall -Wextra -Werror -pedantic cpp-deque-rolling-window-total.cpp -o cpp-deque-rolling-window-total &&
./cpp-deque-rolling-window-total

Observed output:

count=1 total=4
count=2 total=11
count=3 total=13
count=3 total=18
count=3 total=12

How it works

The first two totals cover a partial window. Once three readings are stored, the next update subtracts the outgoing value before removing it. Each update uses end operations without rescanning the window. The compile-time check rules out a zero-sized window and makes the front() call safe when the full-window branch runs.

Limits and choices

The fixed sample fits in long long. Production code needs input bounds or checked arithmetic that also covers the intermediate subtraction and addition. This deque can allocate; it is not a preallocated ring buffer. Allocation failure propagates here, so do not catch it and resume updates as though this sequence were transactional.

The C++ working draft specifies the library operation used here. The example uses the C++20 interface tested above; newer draft additions are outside its scope.

Clean up

rm -- cpp-deque-rolling-window-total.cpp cpp-deque-rolling-window-total
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directory

If the directory is not empty, inspect the remaining files before removing anything else.

Acknowledgements

This post was created with assistance from AI.

Last updated on