Skip to content
Related Articles

Related Articles

Improve Article

Default value of Vector in C++ STL

  • Difficulty Level : Basic
  • Last Updated : 23 Apr, 2020

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:




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

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:




// 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
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :