C++ Basics: Turn Cumulative Readings into Changes
Use std::adjacent_difference to calculate changes between successive cumulative measurements.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and standard-library development headers, with g++ on PATH. You also need Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.
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 1Run the example
Save this as adjacent-difference-cumulative-readings-demo.cpp:
#include <array>
#include <iostream>
#include <numeric>
int main()
{
constexpr std::array<int, 4> totals{10, 15, 14, 20};
std::array<int, 4> changes{};
std::adjacent_difference(totals.begin(), totals.end(), changes.begin());
for (std::size_t i = 0; i < changes.size(); ++i) {
std::cout << i << ": " << changes[i] << '\n';
}
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic adjacent-difference-cumulative-readings-demo.cpp -o adjacent-difference-cumulative-readings-demo &&
./adjacent-difference-cumulative-readings-demoObserved output:
0: 10
1: 5
2: -1
3: 6Read the result
The first result is a copy of the first input: 10. Later results are current minus previous, giving 5, -1, and 6. The decrease from 15 to 14 remains visible because the example uses signed integers.
Apply it carefully
The first result is not a measured change from an earlier reading unless you assume a zero baseline. Supply a real previous reading when needed. Reserve enough output elements and choose a type that can represent every difference; signed overflow is undefined, and unsigned subtraction wraps.
The C++ working draft describes the relevant rules. This example builds in C++20 mode; the current working draft also documents later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- adjacent-difference-cumulative-readings-demo.cpp adjacent-difference-cumulative-readings-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.