Here’s a C++ implementation of the dot product for two vectors, including both a basic loop-based approach and an optimized version using Eigen (a popular linear algebra library for C++).
Method 1: Basic Loop Implementation
#include <vector>
#include <stdexcept> // For std::invalid_argument
double dot_product(const std::vector<double>& v1, const std::vector<double>& v2) {
if (v1.size() != v2.size()) {
throw std::invalid_argument("Vectors must be of the same length.");
}
double result = 0.0;
for (size_t i = 0; i < v1.size(); ++i) {
result += v1[i] * v2[i];
}
return result;
}
Method 2: Using Eigen (Optimized for Performance)
If you're working with numerical computations, Eigen is highly recommended for efficiency:
#include <Eigen/Dense> // Requires Eigen library (install via package manager)
double dot_product_eigen(const Eigen::VectorXd& v1, const Eigen::VectorXd& v2) {
return v1.dot(v2); // Eigen's built-in dot product
}
Example Usage
#include <iostream>
#include <vector>
int main() {
// Example vectors
std::vector<double> vec1 = {1.0, 2.0, 3.0};
std::vector<double> vec2 = {4.0, 5.0, 6.0};
// Using the basic function
double result = dot_product(vec1, vec2);
std::cout << "Dot product (basic): " << result << std::endl; // Output: 32
// Using Eigen (if installed)
Eigen::VectorXd eigen_vec1(3);
eigen_vec1 << 1.0, 2.0, 3.0;
Eigen::VectorXd eigen_vec2(3);
eigen_vec2 << 4.0, 5.0, 6.0;
double eigen_result = dot_product_eigen(eigen_vec1, eigen_vec2);
std::cout << "Dot product (Eigen): " << eigen_result << std::endl; // Output: 32
return 0;
}
Key Notes:
- The dot product is calculated as:
[
\text{dot_product} = \sum_{i=1}^{n} v1_i \times v2_i
]
- If the vectors are of different lengths, the function throws an
std::invalid_argument exception.
- For large datasets, Eigen (
v1.dot(v2)) is much faster than a manual loop.
- To use Eigen, install it via your package manager (e.g.,
sudo apt-get install libeigen3-dev on Ubuntu).
Would you like an extension of this function to handle matrix multiplication as well?