How to Initialize a Vector with Default Values in C++?
Last Updated :
27 Feb, 2024
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++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > vec(5, 10);
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)
Share your thoughts in the comments
Please Login to comment...