c++vectorstdvectorvalarrayinner-product

How can I do a dot product between a matrix and a vector in c++


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);

Solution

  • 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