Home »
        C++ STL
    
    Create a vector by specifying the size and initialize elements with a default value in C++ STL
    
    
    
    
    
    
        C++ STL | vector creation by specify size and values: Here, we are going to learn how to create a vector by specifying the size and initialize the all values with a default value in C++ STL?
        
            Submitted by IncludeHelp, on May 12, 2019
        
    
    
    What is the vector?
    Vector is a container in C++ STL, it is used to represent array and its size can be changed.
    Read more: C++ STL Vector
    Create a vector by specifying the size
    We can create a vector by specifying the size and we can also initialize all elements with a default value while declaring it.
    Here is the syntax to create a vector by specifying the size,
    vector<type> vector_name(size, default_value);
    Here,
    
        - type – is the datatype.
- vector_name – is any use defined name to the vector.
- size – is the initial size of the vector.
- default_value – is the value to initialize all elements.
Example to create/declare vector by specifying the size
    vector::<int> v1(5, 10);
    C++ STL program to create a vector by specifying the size
//C++ STL program to create a vector 
//by specifying the size
#include <iostream>
#include <vector>
using namespace std;
int main()
{
    //vector declaration with size and value
    vector<int> v1(5, 10);
    //printing the vector elements
    //using for each kind of loop
    cout << "Vector v1 elements are: ";
    for (int element : v1)
        cout << element << " ";
    cout << endl;
    //pushing the elements
    v1.push_back(10);
    v1.push_back(20);
    v1.push_back(30);
    v1.push_back(40);
    v1.push_back(50);
    //printing the vector elements
    //using for each kind of loop
    cout << "After pushing the elements\nVector v1 elements are: ";
    for (int element : v1)
        cout << element << " ";
    cout << endl;
    return 0;
}
Output
Vector v1 elements are: 10 10 10 10 10
After pushing the elements
Vector v1 elements are: 10 10 10 10 10 10 20 30 40 50
    
    
  
    Advertisement
    
    
    
  
  
    Advertisement