C++ Standard Library<numeric>
In daily C++ development, we often encounter the following requirements:
- Calculate array sum / product
- Compute prefix sums for range queries
- Batch accumulate to generate a new sequence
- Compute inner product (dot product) between vectors
If you are still writing it by handforLoop, then<numeric>These are exactly the standard library tools you should master.
In the C++ standard library<numeric>The header file provides a set of function templates for numerical calculation. These functions can perform various numerical operations on elements in a container, such as summation, product, minimum, maximum, etc. These function templates are extremely powerful and can be applied to any type of container, including arrays, vectors, lists, and so on.
When using<numeric>Before using the functions in the header file, you need to include this header file in your C++ program:
#include <numeric>
Common Functions
<numeric>is how C++ handlesnumerical sequence computationIt is the core header file, focusing on operations such as reduction, accumulation, and difference, and is compatible with all STL containers;- Basic functions (
accumulate/partial_sum/iotaIt is the core of C++98/11, satisfying most conventional numerical calculation needs; - newly added in C++17
reduce/inclusive_scanParallel functions such as these can significantly improve computational efficiency with large data volumes and need to be used with parallel execution policies.
| Function Name | C++ version | Core functionality | Simplified function prototype (takingvector<int>as an example) |
typical use cases |
|---|---|---|---|---|
accumulate |
C++98 | Computes the cumulative sum of a sequence (a custom binary operation may be specified) | int accumulate(iterator beg, iterator end, int init); |
Calculate array sum, accumulate statistics |
inner_product |
C++98 | Computes the inner product of two sequences (multiply corresponding elements and then accumulate; custom operations may be specified) | int inner_product(iter1 b1, iter1 e1, iter2 b2, int init); |
Vector dot product, weighted sum |
partial_sum |
C++98 | Compute prefix sums of a sequence (the nth result = sum of the first n elements, customizable operation) | void partial_sum(iter b, iter e, iter res); |
Generate prefix sum array, cumulative statistics |
adjacent_difference |
C++98 | Compute differences between adjacent elements in a sequence (the nth result = elem[n] - elem[n-1], customizable operation) | void adjacent_difference(iter b, iter e, iter res); |
Compute differences, detect sequence changes |
iota |
C++11 | Fills a sequence with continuously increasing values (starting from init, incrementing by 1 each time) | void iota(iter b, iter e, T init); |
Generates a sequence of consecutive integers, initializes ordered containers |
reduce |
C++17 | Parallel version of accumulate (similar to accumulate, supports parallel execution, unordered reduction) | T reduce(iter b, iter e, T init = T{}); |
Parallel summation for large data volumes, improving computational efficiency |
transform_reduce |
C++17 | Transformation + reduction (first transform the elements, then accumulate, supports parallel execution) | T transform_reduce(iter1 b1, iter1 e1, iter2 b2, T init); |
Parallel inner product, sum after transformation |
inclusive_scan |
C++17 | Parallel prefix sum (including the current element, similar to partial_sum, supports parallel execution) | void inclusive_scan(iter b, iter e, iter res); |
Parallel generation of prefix sum arrays |
exclusive_scan |
C++17 | Parallel version of prefix sum (excluding current element; the nth result = sum of the first n-1 elements) | void exclusive_scan(iter b, iter e, iter res, T init); |
Parallel generation of prefix sums that do not include the current element |
1. accumulate
accumulateThe function is used to calculate the sum of all elements in a container. It takes three parameters: the container's begin iterator, end iterator, and initial value.
Syntax:
template <InputIterator Iter, class T> T accumulate(Iter first, Iter last, T init);
Example:
Example
#include <numeric>
#include <vector>
int main() {
std::vector<int> v = {1, 2, 3, 4, 5};
int sum = std::accumulate(v.begin(), v.end(), 0);
std::cout << "Sum: " << sum << std::endl; // Output: Sum: 15
return 0;
}
2. inner_product
inner_productThe function is used to calculate the sum of the products of the corresponding elements in two containers.
Syntax:
template <InputIterator1 Iter1, InputIterator2 Iter2, class T> T inner_product(Iter1 first1, Iter1 last1, Iter2 first2, T init);
Example:
Example
#include <numeric>
#include <vector>
int main() {
std::vector<int> v1 = {1, 2, 3};
std::vector<int> v2 = {4, 5, 6};
int product_sum = std::inner_product(v1.begin(), v1.end(), v2.begin(), 0);
std::cout << "Product Sum: " << product_sum << std::endl; // Output: Product Sum: 32
return 0;
}
3. partial_sum
partial_sumThe function computes the partial sums of elements in a container and stores the results in another container.
Syntax:
template <InputIterator InIter, OutputIterator OutIter> OutIter partial_sum(InIter first, InIter last, OutIter result);
Example:
Example
#include <numeric>
#include <vector>
int main() {
std::vector<int> v = {1, 2, 3, 4};
std::vector<int> result(v.size());
std::partial_sum(v.begin(), v.end(), result.begin());
for (int i : result) {
std::cout << i << " "; // Output: 1 3 6 10
}
return 0;
}
4. adjacent_difference
adjacent_differenceThe function computes the differences between adjacent elements in a container and stores the results in another container.
Syntax:
template <InputIterator InIter, OutputIterator OutIter> OutIter adjacent_difference(InIter first, InIter last, OutIter result);
Example:
Example
#include <numeric>
#include <vector>
int main() {
std::vector<int> v = {1, 2, 3, 4};
std::vector<int> result(v.size() - 1);
std::adjacent_difference(v.begin(), v.end(), result.begin());
for (int i : result) {
std::cout << i << " "; // Output: 1 1 1
}
return 0;
}
5. std::gcd
Use std::gcd to compute the greatest common divisor of two integers:
Example
#include <numeric>
int main() {
int a = 48;
int b = 18;
int result = std::gcd(a, b); // Calculate the greatest common divisor of 48 and 18
std::cout << "GCD: " << result << std::endl; // Output 6
return 0;
}
6. std::lcm
Use std::lcm to compute the least common multiple of two integers:
Example
#include <numeric>
int main() {
int a = 48;
int b = 18;
int result = std::lcm(a, b); // Calculate the least common multiple of 48 and 18
std::cout << "LCM: " << result << std::endl; // Output 144
return 0;
}
7. std::iota
Example
#include <numeric> // Include the numeric header file
#include <vector>
int main() {
std::vector<int> v(5); // Create a vector containing 5 elements
// Fill the vector with std::iota, starting at 1
std::iota(std::begin(v), std::end(v), 1);
// Output the filled vector
for (int i : v) {
std::cout << i << " ";
}
std::cout << std::endl; // Output: 1 2 3 4 5
return 0;
}
Use std::iota to fill a range with sequential values.
template<class ForwardIt, class T> void iota(ForwardIt first, ForwardIt last, T value);
8. Find maximum and minimum values
min_elementandmax_elementThe function is used to find the maximum and minimum values in a container.
Example
#include <numeric>
#include <vector>
#include <algorithm> // To use std::min_element and std::max_element
int main() {
// Define a vector of integers
std::vector<int> v = {3, 1, 4, 1, 5, 9};
// Compute the minimum and maximum values
int min_val = *std::min_element(v.begin(), v.end());
int max_val = *std::max_element(v.begin(), v.end());
// Calculate the sum
int sum_val = std::accumulate(v.begin(), v.end(), 0);
// Compute the average
double avg_val = static_cast<double>(sum_val) / v.size();
// Output the results
std::cout << "Min: " << min_val << std::endl;
std::cout << "Max: " << max_val << std::endl;
std::cout << "Sum: " << sum_val << std::endl;
std::cout << "Average: " << avg_val << std::endl;
return 0;
}
The output result is:
Min: 1 Max: 9 Sum: 23 Average: 3.83333other extensions