How to calculate the dot product of two vectors in C++

2 Answers

0 votes
#include <iostream>
#include <vector>
  
// dot product = the sum of the products of the 
//               corresponding entries of the two sequences of numbers  
  
int calculate_dot_product(std::vector<int> &v1, std::vector<int> &v2) {
    int product = 0;
      
    for (int i = 0; i < v1.size(); i++)
        product += v1[i] * v2[i];
      
    return product;
}
  
int main() {
    std::vector<int> v1 { 1, 4, 8, 9, 6 };
    std::vector<int> v2 { 0, 7, 1, 3, 40 };
    
    // 1 * 0 + 4 * 7 + 8 * 1 + 9 * 3 + 6 * 40 = 0 + 28 + 8 + 27 + 240 = 303
      
    std::cout << "Dot product = " << calculate_dot_product(v1, v2);
}
  
  
  
  
/*
run:
  
Dot product = 303
  
*/

 



answered Feb 14, 2023 by avibootz
edited Jun 18, 2024 by avibootz
0 votes
#include <iostream>
#include <vector>
#include <numeric>

int main() {
    std::vector<int> v1 { 1, 4, 8, 9, 6 };
    std::vector<int> v2 { 0, 7, 1, 3, 40 };
    
    std::cout << "Dot product = " << inner_product(v1.begin(), v1.end(), v2.begin(), 0);
}




/*
run:

Dot product = 303

*/

 



answered Feb 14, 2023 by avibootz
...