LAST UPDATED: NOVEMBER 1, 2020
C++ Program Initialising a Vector in STL (Part 1)
Hello Everyone!
In this tutorial, we will learn about the various ways of initializing a Vector (Part 1), in the C++ programming language.
What are Vectors?
Vectors are the same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted. This makes them more advantageous over the ordinary Arrays which are of fixed size and are static in nature.
To learn more about Vectors in CPP, we will recommend you to visit STL Vector Container
For better understanding, refer to the well-commented C++ code given below.
Code:
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << " ===== Program to demonstrate the various ways of Initializing a Vector (Part 1), in CPP ===== \n\n";
cout << "Method 1: Using push_back() method\n\n";
//create an empty vector
vector<int> v;
//insert elements into the vector
v.push_back(1);
v.push_back(2);
v.push_back(3);
//prining the vector
cout << "The elements of the first vector are: ";
for (int i : v)
{
cout << i << " ";
}
cout << "\n\n\n\n\nMethod 2: Initializing all the elements with a specific value\n\n";
//creating a vector of size 5 with all values initalized to 10
vector<int> v1(5, 10);
//prining the vector
cout << "The elements of the second vector are: ";
for (int i : v1)
{
cout << i << " ";
}
cout << "\n\n\n";
return 0;
}
Output:
We hope that this post helped you develop a better understanding of the concept of Vector and its implementation in C++. For any query, feel free to reach out to us via the comments section down below.
Keep Learning : )