Site Tools


wiki:hpp-numeric

Table of Contents

<numeric>

<numeric> provides numeric algorithms: std::accumulate (sum), std::inner_product (dot product), std::adjacent_difference, std::partial_sum, std::iota (fill with sequence).

Use these for numerical operations on ranges; they work with any container that has iterators.

Example

This example computes a sum and a dot product of two vectors using numeric algorithms.

// compile: g++ -std=c++11 -o numericexample numericexample.cpp
// run: ./numericexample
// description: accumulate and inner_product
 
#include <numeric>
#include <vector>
#include <iostream>
 
int main() {
    std::vector<int> a = {1, 2, 3};
    std::vector<int> b = {4, 5, 6};
 
    int sum = std::accumulate(a.begin(), a.end(), 0);
    std::cout << "sum of a: " << sum << "\n";
 
    int dot = std::inner_product(a.begin(), a.end(), b.begin(), 0);
    std::cout << "dot product: " << dot << "\n";
 
    return 0;
}
wiki/hpp-numeric.md · Last modified: by 127.0.0.1