Open In App

How to Initialize a Vector with Zero in C++?

Last Updated : 03 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Initializing a vector with value zero means assigning the initial value 0 to all elements of vector. In this article, we will learn the different methods to initialize the vector with zero in C++.

The simplest method to initialize a vector with zeros is by using vector constructor. Let's take a look at an example:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {

    // Initialize the vector with 0
    vector<int> v(5, 0);
  
    for (auto i : v)
        cout << i << " ";
    return 0;
}

Output
0 0 0 0 0 

Note: If we do not provide any value in this method, then by default the vector will initialize with value 0.

Apart from the above method, C++ also provides other different methods to initialize a vector with 0. Some of them are:

One by One Initialization

To initialize the vector with value 0, we can insert the value 0 in the vector one by one using vector push_back() method.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v;

    // Initialize the vector with 0
    for (int i = 0; i < 5; i++)
        v.push_back(0);
  
    for (auto i : v)
        cout << i << " ";
    return 0;
}

Output
0 0 0 0 0 

Using Vector assign()

The vector assign() method assigns the size of vector as well as it can also initialize the vector with some value like 0 in this case.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v;

    // Initialize the vector with 0
    v.assign(5, 0);
  
    for (auto i : v)
        cout << i << " ";
    return 0;
}

Output
0 0 0 0 0 

Using fill()

The fill() method is used to fill the vector of given range with some specific value. So, to initialize the vector with value 0, we have to pass the specific value as 0.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v(5);

    // Initialize the vector with 0
    fill(v.begin(), v.end(), 0);
  
    for (auto i : v)
        cout << i << " ";
    return 0;
}

Output
0 0 0 0 0 



Next Article
Article Tags :
Practice Tags :

Similar Reads