Element wise multiplication of two vectors in C++
In this tutorial, we will learn how to do Element wise multiplication of two vectors in C++. First of all, we must have a basic understanding of vectors in C++. Arrays are static as once we declare their size their size remains unchanged. Vectors are Dynamic Arrays meaning we can change their size even after initiation. They are very useful as we can change their size when required.
Element-wise multiplication of two vectors in C++
Element-wise multiplication of two vectors in C++ requires a prerequisite understanding of vectors. Be sure to check out:
First, we will be taking two input vectors named “v1
” and “v2
“. We have used these vector elements as {1,2,3,4,5}
for easy understanding of the code.
#include <bits/stdc++.h> using namespace std; int main(){ vector<int> v1={1,2,3,4,5}; vector<int> v2={1,2,3,4,5};
Then we will create a “product” vector to store element wise products of elements in both vectors “v1” and “v2”. We will multiply each of the respective elements in vectors, like v1[i]
and v2[i]
( i is the index of the element in vectors). We will run a for loop and push the products i.e v1[i] *v2[i]
in the product vector. Vectors have inbuilt functions in vector stl like push_back() to store the elements in the vector.
vector<int> product; for(int i=0;i<v1.size();i++){ product.push_back(v1[i]*v2[i]); }
Then we will print the resultant vector which is the product vector.
cout<<"Product vector is:"<<endl; for(int i=0;i<product.size();i++){ cout<<product[i]<<" "; }
Here is the full code in C++:
#include<bits/stdc++.h> using namespace std; int main(){ vector<int> v1={1,2,3,4,5}; vector<int> v2={1,2,3,4,5}; vector<int> product; for(int i=0;i<v1.size();i++){ product.push_back(v1[i]*v2[i]); } cout<<"Product vector is:"<<endl; for(int i=0;i<product.size();i++){ cout<<product[i]<<" "; } }
Output:
Product vector is: 1 4 9 16 25
Leave a Reply