C++ Vector
C++ Vector
C++ Vector
• A vector is a sequence container class that implements dynamic array, means
size automatically changes when appending elements. A vector stores the
elements in contiguous memory locations and allocates the memory as needed
at run time.
Syntax
Consider a vector 'v1’.
Syntax would be:
vector<object_type> v1;
Rakesh Sharma
#include<iostream>
#include<vector>
int main()
{
vector<string> v1;
v1.push_back(“Rakesh ");
v1.push_back(“Sharma");
for( vector<string>::iterator itr=v1.begin(); itr!=v1.end(); itr++)
cout<<*itr;
return 0;
}
Rakesh Sharma
Output: Rakesh Sharma
C++ Vector Functions
Function Description
at() It provides a reference to an element.
Rakesh Sharma
#include<iostream>
#include<vector>
void main()
{
vector <int> v1{1,2,3,4};
for(int i=0;i<v1.size();i++)
cout<<v1.at(i);
}
Output:
1234
Rakesh Sharma
C++ Vector push_back()
• This function adds a new element at the end of the vector.
Syntax
Consider a vector v and 'k' is the value.
Syntax would be:
v.push_back(k)
Parameter
k: k is the value which is to be inserted at the end of the vector.
Rakesh Sharma
#include<iostream>
#include<vector>
void main()
{
vector<char> v;
v.push_back(‘m');
v.push_back(‘a');
v.push_back(‘n');
v.push_back(‘0');
v.push_back(‘j');
for(int i=0; i<v.size(); i++)
cout<<v[i];
}
Output: manoj
Rakesh Sharma
#include<iostream>
#include<vector>
void main()
{
vector<int> v;
v.push_back( 1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
for(int i=0; i<v.size(); i++)
cout<<v[i];
}
Output:1 2 3 4 5
Rakesh Sharma
Vector pop_back()
• It deletes the last element and reduces the size of the vector by one.
Syntax
Consider a vector v.
Syntax would be:
v.pop_back();
Parameter
It does not contain any parameter.
Rakesh Sharma
#include<iostream>
#include<vector>
int main()
{
vector<string> v{"welcome","to",“Amrapali",“University"};
cout<<"Initial string is :";
for(inti=0;i<v.size();i++)
cout<<v[i]<<" ";
cout<<'\n';
cout<<"After deleting last string, string is :";
v.pop_back();
for(int i=0;i<v.size();i++)
cout<<v[i]<<" ";
return 0;
}
Rakesh Sharma
• Output:
Rakesh Sharma