Cpp Libs Numeric
In daily C++ development, we often encounter the following needs:
* Calculate array sum / product
* Calculate prefix sums for range queries
* Batch accumulation to generate new sequences
* Calculate dot product between vectors
If you're still writing `for` loops manually, then `` is the standard library tool you should master.
The `` header file in the C++ standard library provides a set of function templates for numerical calculations. These functions can perform various numerical operations on elements in containers, such as sum, product, minimum, maximum, etc. These function templates are very powerful and can be applied to any type of container, including arrays, vectors, lists, etc.
Before using functions from the `` header file, you need to include this header file in your C++ program:
#include
## Common Functions
* `` is the core header file for **numerical sequence computation** in C++, focusing on reduction, accumulation, difference operations, and is compatible with all STL containers;
* Basic functions (`accumulate`/`partial_sum`/`iota`) are the core of C++98/11, meeting most conventional numerical computation needs;
* Parallel functions added in C++17 such as `reduce`/`inclusive_scan` can significantly improve computational efficiency for large data volumes, and need to be used with parallel execution policies.
| Function Name | C++ Version | Core Functionality | Simplified Function Prototype (using `vector` as example) | Typical Application Scenarios |
| --- | --- | --- | --- | --- |
| `accumulate` | C++98 | Calculate cumulative sum of sequence (can customize binary operation) | `int accumulate(iterator beg, iterator end, int init);` | Calculate array sum, accumulate statistics |
| `inner_product` | C++98 | Calculate inner product of two sequences (multiply corresponding elements and accumulate, can customize operation) | `int inner_product(iter1 b1, iter1 e1, iter2 b2, int init);` | Vector dot product, weighted sum |
| `partial_sum` | C++98 | Calculate prefix sums of sequence (nth result = sum of first n elements, can customize operation) | `void partial_sum(iter b, iter e, iter res);` | Generate prefix sum array, cumulative statistics |
| `adjacent_difference` | C++98 | Calculate difference between adjacent elements in sequence (nth result = elem-elem, can customize operation) | `void adjacent_difference(iter b, iter e, iter res);` | Calculate differences, detect sequence changes |
| `iota` | C++11 | Fill sequence with continuously incrementing values (starting from init, increment by 1 each time) | `void iota(iter b, iter e, T init);` | Generate consecutive integer sequence, initialize ordered container |
| `reduce` | C++17 | Parallel version of accumulation (similar to accumulate, supports parallel execution, unordered reduction) | `T reduce(iter b, iter e, T init = T{});` | Large data volume parallel summation, improve computational efficiency |
| `transform_reduce` | C++17 | Transform + reduce (first transform elements, then accumulate, supports parallel) | `T transform_reduce(iter1 b1, iter1 e1, iter2 b2, T init);` | Parallel computation of inner product, sum after transformation |
| `inclusive_scan` | C++17 | Parallel version of prefix sum (includes current element, similar to partial_sum, supports parallel) | `void inclusive_scan(iter b, iter e, iter res);` | Parallel generation of prefix sum array |
| `exclusive_scan` | C++17 | Parallel version of prefix sum (does not include current element, nth result = sum of first n-1 elements) | `void exclusive_scan(iter b, iter e, iter res, T init);` | Parallel generation of prefix sums "not including self" |
### 1. `accumulate`
The `accumulate` function is used to calculate the sum of all elements in a container. It accepts three parameters: the starting iterator of the container, the ending iterator, and the initial value.
**Syntax**:
template T accumulate(Iter first, Iter last, T init);
**Example**:
## Example
#include
#include
#include
int main(){
std::vector 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`
The `inner_product` function is used to calculate the sum of products of corresponding elements from two containers.
**Syntax**:
template T inner_product(Iter1 first1, Iter1 last1, Iter2 first2, T init);
**Example**:
## Example
#include
#include
#include
int main(){
std::vector v1 ={1, 2, 3};
std::vector 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`
The `partial_sum` function is used to calculate the partial sums of elements in a container and store the results in another container.
**Syntax**:
template OutIter partial_sum(InIter first, InIter last, OutIter result);
**Example**:
## Example
#include
#include
#include
int main(){
std::vector v ={1, 2, 3, 4};
std::vector 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`
The `adjacent_difference` function is used to calculate the differences between adjacent elements in a container and store the results in another container.
**Syntax**:
template OutIter adjacent_difference(InIter first, InIter last, OutIter result);
**Example**:
## Example
#include
#include
#include
int main(){
std::vector v ={1, 2, 3, 4};
std::vector 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 calculate the greatest common divisor of two integers:
## Example
#include
#include
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 calculate the least common multiple of two integers:
## Example
#include
#include
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
#include // Include numeric header file
#include
int main(){
std::vector v(5);// Create a vector containing 5 elements
// Use std::iota to fill the vector, starting from value 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 sequence values within a range.
templatevoid iota(ForwardIt first, ForwardIt last, T value);
### 8. Finding Maximum and Minimum Values
The `min_element` and `max_element` functions are used to find the maximum and minimum values in a container.
## Example
#include
#include
#include
#include // For using std::min_element and std::max_element
int main(){
// Define a vector containing integers
std::vector v ={3, 1, 4, 1, 5, 9};
// Calculate 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 sum
int sum_val = std::accumulate(v.begin(), v.end(), 0);
// Calculate average
double avg_val =static_cast(sum_val)/ v.size();
// Output 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;
}
Output results:
Min: 1Max: 9Sum: 23Average: 3.83333
YouTip