Skip to content
C++ Basics: Compute a Weighted Total with inner_product

C++ Basics: Compute a Weighted Total with inner_product

November 7, 2026

Use inner_product to multiply corresponding quantities and prices, then add the products into a sufficiently wide total.

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 1

Run the example

Save this as inner-product-weighted-total-demo.cpp:

#include <array>
#include <iostream>
#include <numeric>

int main()
{
    const std::array<long long, 3> quantities{2, 3, 1};
    const std::array<long long, 3> price_cents{150, 200, 999};
    static_assert(quantities.size() == price_cents.size());
    const auto total = std::inner_product(quantities.begin(), quantities.end(),
                                         price_cents.begin(), 0LL);
    std::cout << "total cents: " << total << '\n';
}

Compile and run it. The program runs only after compilation succeeds:

g++ -std=c++20 -Wall -Wextra -Werror -pedantic inner-product-weighted-total-demo.cpp -o inner-product-weighted-total-demo &&
./inner-product-weighted-total-demo

Observed output:

total cents: 1899

Read the result

The three line totals are 300, 600 and 999 cents, producing 1899 cents. Both input arrays and the initial accumulator use long long.

Apply it carefully

The algorithm receives no end iterator for the second range: provide at least as many elements as the first range. A wide initial value widens the accumulator but does not automatically widen multiplication of narrower input types. Here the inputs are already wide; real untrusted quantities still need bounds checks for both each product and the running sum. Integer cents avoid fractional rounding in this example.

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 -- inner-product-weighted-total-demo.cpp inner-product-weighted-total-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directory

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

Acknowledgements

This post was created with assistance from AI.

Last updated on