Open In App

How to Initialize a Vector with Default Values in C++?

Last Updated : 25 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Initialization is the process of assigning the value to the elements of vector. In this article, we will learn how to initialize the vector with default value in C++.

The simplest method to initialize the vector with default value is by using constructor during declaration. Let’s take a look at a simple example:

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

int main() {

    // Initialze vector with default value 9
    vector<int> v(5, 9);

    for (auto i : v)
        cout << i << " ";
    return 0;
}

Output
9 9 9 9 9 

There are also some other methods in C++ to initialize the vector with default value. Some of them are as follows:

Using Vector assign()

The vector assign() method can also be used to assign the existing vector with specified size and some default value.

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

int main() {
    vector<int> v;

    // Initialze vector with default value 9
    v.assign(5, 9);

    for (auto i : v)
        cout << i << " ";
    return 0;
}

Output
9 9 9 9 9 

Using fill()

In this method, first we create the vector with specified size and then we fill the vector with default value using fill() method.

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

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

    // Initialze vector with default value 9
    fill(v.begin(), v.end(), 9);

    for (auto i : v)
        cout << i << " ";
    return 0;
}

Output
9 9 9 9 9 

Note: With this method, we can initialize the range of vector with default value.

Using iota()

If we want to initialize our vector with sequential default value, then simply we can use iota() method.

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

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

    // Initialze vector with sequential default value
    // starting with 9
    iota(v.begin(), v.end(), 1);

    for (auto i : v)
        cout << i << " ";
    return 0;
}

Output
1 2 3 4 5 

Next Article
Article Tags :
Practice Tags :

Similar Reads