Open In App

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

Last Updated : 27 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, vectors are similar to arrays but unlike arrays, they are dynamic in nature. Vectors can resize them automatically when elements are inserted or removed during the runtime. In this article, we will learn how we can initialize a vector with default values in C++.

Example:

Input:
vec ={, , , , , };
// Intialized the vector with default value 10

Output:
Elements in the vector are: 10 10 10 10 10

Initialize a Vector with Default Values in C++

To initialize a vector with default values in C++, the most straightforward way is to use the vector constructor that takes the size of the vector and the default value to initialize as arguments. The constructor function initializes the vector with the provided default value directly.

C++ Program to Initialize a Vector with Default Values

C++




// C++ program to Initialize a Vector with Default Values
#include <iostream>
#include <vector>
using namespace std;
  
// Driver Code
int main()
{
    // Initializing a vector of size 5 with default value as
    // 10 using constructor
    vector<int> vec(5, 10);
  
    // Print the elements of the vector
    cout << "Elements in vector are: ";
    for (auto ele : vec) {
        cout << ele << " ";
    }
    return 0;
}


Output

Elements in vector are: 10 10 10 10 10 

Time Complexity: O(N) where N is the size of the vector.
Auxiliary Space: O(1)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads