Open In App

Default value of Vector in C++ STL

Improve
Improve
Like Article
Like
Save
Share
Report

Vectors are the same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. By default, the size of the vector automatically changes when appending elements. To initialize the map with a random default value, below is the approach: Approach:

  1. Declare a vector.
  2. Set the size of the vector to the user defined size N

Default value of the Vector:

The default value of a vector is 0. Syntax:

// For declaring 
vector v1(size); 

// For Vector with default value 0
vector v1(5);

Below is the implementation of the above approach: 

CPP




// C++ program to create an empty
// vector with default value
 
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    int n = 3;
 
    // Create a vector of size n with
    // all values as 0.
    vector<int> vect(n);
 
    for (int x : vect)
        cout << x << " ";
 
    return 0;
}


Output:

0 0 0

Time Complexity: O(1)
Auxiliary Space: O(N)

Specifying a default value for the Vector:

We can also specify a random default value for the vector. In order to do so, below is the approach: Syntax:

// For declaring 
vector v(size, default_value);

// For Vector with a specific default value
// here 5 is the size of the vector
// and  10 is the default value
vector v1(5, 10);

Below is the implementation of the above approach: 

CPP




// C++ program to create an empty vector
// and with a specific default value
 
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    int n = 3;
    int default_value = 10;
 
    // Create a vector of size n with
    // all values as 10.
    vector<int> vect(n, default_value);
 
    for (int x : vect)
        cout << x << " ";
 
    return 0;
}


Output:

10 10 10

Time Complexity: O(N)
Auxiliary Space: O(1)



Last Updated : 21 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads