In: Computer Science
Write a program in C++ using a vector to create the following output.
Starting with 2, pushing these into the back of the vector: 2, 4, 6, 8, 10
|
The size of the list is now 5.
The vector capacity (array size) is 6.
The back element is: 10
The front element is: 2
Now deleting the value at the end of the list . . .
The size of the list is now 4.
|
After deleting, here is the list: 2, 4, 6, 8
Now swapping the first number with the last number.
After swapping, here is the list: 8, 4, 6, 2
Now inserting 0 at the beginning of the list.
After inserting, here is the list: 0, 8, 4, 6, 8
The size of the list is now 5.
The value of the third element (index 2) is: 4
Now removing all list items . . .
The size of the list is now 0.
The vector capacity (array size) is 6.
#include<bits/stdc++.h>// <bits/stdc++.h> header
file includes all the headers required such as vector, algorithm,
etc
using namespace std;
int main(){
vector<int> numbers;
numbers.push_back(2);
numbers.push_back(4);
numbers.push_back(6);
numbers.push_back(8);
numbers.push_back(10);
cout<<"Size of list:-
"<<numbers.size()<<endl;
cout<<"Values of list are:- \n";
for(int i=0;i<numbers.size();i++)
cout<<numbers[i]<<" ";
cout<<endl;
cout<<"Back element in list:-
"<<numbers[numbers.size()-1]<<endl;
cout<<"Front element in list:-
"<<numbers[0]<<endl;
numbers.pop_back();
cout<<"After deleting back element from list, size of the
list is:- "<<numbers.size()<<endl;
cout<<"List elements after deleting back element are:-
\n";
for(int i=0;i<numbers.size();i++){
cout<<numbers[i]<<" ";
}
cout<<endl;
cout<<"Swapping first and last element of the list:-
\n";
swap(numbers[0], numbers[numbers.size()-1]);
cout<<endl;
cout<<"After swapping first and last element, list elements
are:- \n";
for(int i=0;i<numbers.size();i++){
cout<<numbers[i]<<" ";
}
cout<<endl;
cout<<"Inserting 0 at the begining of the list:- \n";
auto it = numbers.insert(numbers.begin(), 0);
cout<<"After inserting, list elements are:- \n";
for(int i=0;i<numbers.size();i++){
cout<<numbers[i]<<" ";
}
cout<<endl;
cout<<"Size of list:-
"<<numbers.size()<<endl;
cout<<"The value of the third element (index 2) is:-
"<<numbers[2]<<endl;
cout<<"Now removing all list items . . ."<<endl;
numbers.clear();
cout<<"Size of list:-
"<<numbers.size()<<endl;
return 0;
}
Note: Capacity of list is compiler dependent, it is not necessarily
equal to the vector size. It can be equal to or greater, with the
extra space
Please refer to the screenshot of the code to understand the indentation of the code.
Please refer to the screenshot of the Output to understand in a better way.