Numeric

The numeric header file contains template functions that perform numeric operations on ranges of elements.

namespace utils

Functions

template<typename InputIt, typename T>
T product(InputIt first, const InputIt last, T init)

Computes the product of a range of elements.

This function calculates the product of the elements in the range [first, last) starting with the initial value init.

Template Parameters:
  • InputIt – Input iterator type for the range.

  • T – The type of the initial value and the result.

Parameters:
  • first – The beginning of the range.

  • last – The end of the range.

  • init – The initial value to start the product.

Returns:

T The product of the elements in the range.

template<typename InputIt>
remove_cvref_t<decltype(*first)> mean(InputIt first, const InputIt last)

Computes the mean of a range of elements.

This function calculates the mean (average) of the elements in the range [first, last).

Note

The return type is the same as the type of the elements in the range. Overflow may occur.

Template Parameters:

InputIt – Input iterator type for the range.

Parameters:
  • first – The beginning of the range.

  • last – The end of the range.

Returns:

decltype(*first) The mean of the elements in the range.

template<typename T, typename InputIt>
T mean(InputIt first, const InputIt last)

Computes the mean of a range of elements.

This function calculates the mean (average) of the elements in the range [first, last).

Note

If type T is incorrectly specified, overflow may occur.

Template Parameters:
  • T – The type of the result.

  • InputIt – Input iterator type for the range.

Parameters:
  • first – The beginning of the range.

  • last – The end of the range.

Returns:

T The mean of the elements in the range.

Usage

The following examples demonstrates how to use the numeric header file:

  • product

const std::vector vec{1, 2, 3, 4};
const auto result{utils::product(vec.begin(), vec.end(), 1)};
std::cout << "result: " << result << std::endl;

Output:

result: 24
  • mean

const std::vector vec{1, 2, 3, 4, 5};
const auto result{utils::mean(vec.begin(), vec.end())};
std::cout << "result: " << result << std::endl;

Output:

result: 3
  • mean [with type]

constexpr auto int32_max{std::numeric_limits<std::int32_t>::max()};
const std::vector<std::int32_t> vec(3, int32_max);
const auto result{utils::mean<std::int64_t>(vec.begin(), vec.end())};
std::cout << std::boolalpha
          << "result == int32_max: " << (result == int32_max) << std::endl;

Output:

result == int32_max: true