Vector in C++ STL

This article provides the example of implementation of Vector in C++. Vector is a template class in STL (Standard Template Library) in C++ language. It is used to work with dynamic data.

Vectors can resize automatically, depending on the insertion and deletion of elements. Here is an example of implementation of vector class.

#include<iostream>
#include<vector>
using namespace std;
int main(){
	vector<int> v(5);
	cout<<"The size of vector is ";
	cout<<v.size()<<endl;
	cout<<"The capacity of vector is ";
	cout<<v.capacity()<<endl;
	for(int i=0;i<(int)v.size();i++){
		v[i] = i*5;
	}
	cout<<"The elements of the vectors";
	for(int i=0;i<(int)v.size();i++){
		cout<<" "<<v[i];
	}
	cout<<endl<<"Two elements pushed back "<<endl;
	v.push_back(10);
	v.push_back(12);
	cout<<"The size of vector is ";
	cout<<v.size()<<endl;
	cout<<"The capacity of vector is ";
	cout<<v.capacity()<<endl;
	cout<<"The elements of the vectors";
	for(int i=0;i<(int)v.size();i++){
		cout<<" "<<v[i];
	}
	cout<<endl<<"The element at the front is "<<v.front()<<endl;
	cout<<"The element at the back is "<<v.back()<<endl;
	cout<<"Assigning 25 at number 3 using []"<<endl;
	v[3]=25;
	cout<<"The element at 3 using v.at() is "<<v.at(3)<<endl;
	cout<<"The elements of the vectors";
	for(int i=0;i<(int)v.size();i++){
		cout<<" "<<v[i];
	}
	v.pop_back();
	cout<<endl<<"The elements of the vectors";
	for(int i=0;i<(int)v.size();i++){
		cout<<" "<<v[i];
	}
	cout<<endl<<"Is the vector empty : "<<v.empty()<<endl;
	v.clear();
	cout<<"Is the vector empty : "<<v.empty()<<endl;
	return 0;
}
output of the above program. vector class implementation.
output of the above program. vector class implementation.

In this program we have seen following methods

  • size()
  • capacity()
  • [ ] – assignment operator
  • push_back()
  • pop_back()
  • at()
  • empty()
  • clear()

Leave a Reply