Introduction
In this lab, we will learn about the different ways to initialize a vector in C++. We will cover the following methods:
In this lab, we will learn about the different ways to initialize a vector in C++. We will cover the following methods:
The push_back()
method is used to insert elements into the vector dynamically one at a time. This method increases the size of the vector by one and inserts the new element at the end of the vector.
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
cout << "Using push_back() method\n\n";
//create an empty vector
vector<int> v;
//insert elements into the vector using push_back()
v.push_back(1);
v.push_back(2);
v.push_back(3);
//prining the vector
cout << "The elements of the vector are: ";
for (int i : v)
{
cout << i << " ";
}
cout << "\n\n\n";
return 0;
}
To compile and run the above code, open the terminal and navigate to the file location ~/project
. Type the following command to compile and run the program:
g++ main.cpp -o main && ./main
We can initialize all the elements in the vector with a specific value using the following constructor:
vector<int> v1(n, value);
Here, n
represents the number of elements we want to initialize and value
represents the value to which all the elements are to be initialized.
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
cout << "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);
//printing the vector
cout << "The elements of the vector are: ";
for (int i : v1)
{
cout << i << " ";
}
cout << "\n\n\n";
return 0;
}
To compile and run the above code, open the terminal and navigate to the file location ~/project
. Type the following command to compile and run the program:
g++ main.cpp -o main && ./main
In this lab, we have learned about the different ways to initialize a vector in C++ using push_back() method and constructor. We have learned how vectors are beneficial over arrays due to their dynamic size and ability to resize automatically. We have also demonstrated C++ code to understand and implement the above methods. You can now write your own code using these methods to initialize vectors in C++.