3

There are a function called inner_product, but I failed miserably in use that. I'll need to use this function several times for different matrices and vectors. Bellow my current code:

std::vector<vector<int>> matrix_a = {{0, 0},
                                     {0, 1},
                                     {1, 0},
                                     {1, 1}};
std::vector<float> vector_b = {0.5, 0.8};

dot_produt(matrix_a, vettor_b);
float dot_produt(vector<vector<int>> e, vector<float> p){
    return std::inner_product(std::begin(e), std::end(e), std::begin(p), 0.0);
}

The process is like:

(0.5 * 0) + (0.8 * 0) + (0.5 * 0) + (0.8 * 1)... ...

Expected output:

2.6

Error:

no match for 'operator*' (operand types are 'std::vector<int>' and 'float')
__init = __init + (*__first1 * *__first2);
anastaciu
  • 23,467
  • 7
  • 28
  • 53
messier
  • 65
  • 1
  • 7
  • I don't quite understand why you expect this to work as-is. `vector`s and `float`s aren't something you can arithmetically compare? – Asteroids With Wings May 06 '20 at 21:16
  • I was under the impression that the dot product is between two vectors. You'd use the dot product on rows and columns of a matrix, but not on the whole thing. – Kenny Ostrom May 06 '20 at 21:17

1 Answers1

3

You are trying to use pointers to begin and end of a vector of vectors, inner_product requires pointers to beginning and end of a vector.

Also, vectors have their own iterators, you can use them instead of std::begin and std::end.

Live demo

#include <iostream>
#include <numeric>
#include <vector>

//passing vectors by reference avoids unnecessary copies
double dot_produt(const std::vector<std::vector<int>> &e, const std::vector<float> &p)
{
    double result = 0;
    for (auto& v : e) //range based loop
        result += std::inner_product(v.begin(), v.end(), p.begin(), 0.0);
    return result;
}

int main()
{
    std::vector<std::vector<int>> matrix_a = {{0, 0},
                                              {0, 1},
                                              {1, 0},
                                              {1, 1}};
    std::vector<float> vector_b = {0.5, 0.8};

    std::cout << dot_produt(matrix_a, vector_b); //test print
}

Output:

2.6
anastaciu
  • 23,467
  • 7
  • 28
  • 53