example2_inner_product.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <vector>
#include <numeric>

int main() {
    std::vector<int> v1 = {1, 2, 3, 4, 5};
    std::vector<int> v2 = {10, 20, 30, 40, 50};

    // Compute inner product
    int inner_prod = std::inner_product(v1.begin(), v1.end(), v2.begin(), 0);
    std::cout << "Inner product: " << inner_prod << std::endl;

    // Custom inner product: sum of products of corresponding elements minus 1
    int custom_prod = std::inner_product(v1.begin(), v1.end(), v2.begin(), 0,
                                         std::plus<>(),
                                         [](int a, int b) { return a * b - 1; });
    std::cout << "Custom inner product: " << custom_prod << std::endl;

    return 0;
}
Back to numeric