Set all elements of vector to 0 in C++
Given a vector of elements, the task is to set all elements to zero in C++.
When a vector is created, all its values are initialized to zero.
The following code will help you understand this:
#include<bits/stdc++.h> using namespace std; int main() { vector<int> v(5); // Creating a vector of size 5 for (int i=0; i<v.size(); i++) // Printing default values cout << v[i]<<" "; }
Output: 0 0 0 0 0
But if we are given a vector containing some elements we can set those elements to zero by using different methods. For example,
Input: v={1, 2, 3, 4, 5}
Output: 0 0 0 0 0
Let’s see some ways of doing this:
1. Using for loop
In this method, we will use for loop for modifying the elements of the vector to zero. We will traverse the vector using the iterator i ranging from i=0 to i=v.size()-1(last element).
The following C++ code will illustrate this method:
#include<bits/stdc++.h> using namespace std; int main() { vector<int> v={1, 2, 3, 4, 5}; // Creating a vector cout<<"Original Vector:"<<endl; for (int i=0; i<v.size(); i++) { cout << v[i]<<" "; } cout<<endl; cout<<"Modified Vector"<<endl; for (int i=0; i<v.size(); i++) { v[i]=0; cout <<v[i]<<" "; } }
Output: Original Vector: 1 2 3 4 5 Modified Vector 0 0 0 0 0
2. Using fill()
The fill()
function can be used to assign a particular value to all the elements in the vector in the range begin() and end().
Syntax: fill(v.begin(), v.end(), value);
#include<bits/stdc++.h> using namespace std; int main() { vector<int> v={1, 2, 3, 4, 5}; // Creating a vector cout<<"Original Vector:"<<endl; for (int i=0; i<v.size(); i++) { cout << v[i]<<" "; } cout<<endl; fill(v.begin(), v.end(), 0); cout<<"Modified Vector"<<endl; for (int i=0; i<v.size(); i++) { cout <<v[i]<<" "; } }
Output: Original Vector: 1 2 3 4 5 Modified Vector 0 0 0 0 0
Also read: How to convert a string to a vector of chars in C++
Leave a Reply