Default value of Vector in C++ STL

Vectors are 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

0 0 0

Specifying a default value for the Vector:

We can also specify a random default value for the vector. Inorder 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

10 10 10

Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.




My Personal Notes arrow_drop_up

before giving up , just think why u started

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.