Animesh Srivastava
Animesh Srivastava

Reputation: 7

C++: Inner Product

In this program how's the

  1. inner_product(series1,series1+3,series2,init,minus(),divides())
  2. inner_product(series1,series1+3,series2,init,myaccumulator,myproduct)

are computed ?

// inner_product example
#include <bits/stdc++.h>
using namespace std;
int myaccumulator (int x, int y) {return x+y;}
int myproduct (int x, int y) {return x+y;}

int main () {
    int init = 100;
    int series1[] = {10,20,30};
    int series2[] = {1,2,3};

    cout << "using default inner_product: ";
    cout << inner_product(series1,series1+3,series2,init);
    cout << '\n';

    cout << "using functional operations: ";
    cout << inner_product(series1,series1+3,series2,init,minus<int>(),divides<int>());
    cout << '\n';

    cout << "using custom functions: ";
    cout << inner_product(series1,series1+3,series2,init,myaccumulator,myproduct);
    cout << '\n';

    return 0;
}

using default inner_product: 240 using functional operations: 70 using custom functions: 34

Upvotes: 0

Views: 317

Answers (1)

Blastfurnace
Blastfurnace

Reputation: 18652

The default operations for std::inner_product are plus and multiplies so the first call computes:

100 + (10 * 1) + (20 * 2) + (30 * 3)

and the result is 240.

The second call using minus and divides computes:

100 - (10 / 1) - (20 / 2) - (30 / 3)

and the result is 70.

The third call using the functions you provided computes:

100 + (10 + 1) + (20 + 2) + (30 + 3)

and the result is 166, not 34 as claimed in your question.

Demo running on Compiler Explorer

Upvotes: 2

Related Questions