More Methods in Vector STL

This article will shows you some more methods in the vector class. Methods like swap, insert, emplace, data, erase, clear, begin and end are implemented in the program below.

  • swap function swaps two vectors.
  • insert function inserts the element at the particular location.
  • emplace function inserts the element at the particular location.
  • emplace_back function inserts the element at the last.
  • data function points to the beginning of the vector.
  • erase function removes the data at the location.
  • clear function removes all the data from the vector.
#include<iostream>
#include<vector>
using namespace std;
template <class T>
void traverse(vector<T> v){
	cout<<"The elements are : ";
	if(v.empty()){
		cout<<0;
	}
	else{
		for(auto i=v.begin();i!=v.end();i++){
			cout<<*i<<" ";
		}
		cout<<endl;
	}
}
int main(){
	vector<char> v;
	v.push_back('#');
	v.push_back('A');
	
	vector<char> v1;
	v1 = v;
	v1[0] = '7';
	v1[1] = '9';
	
	traverse(v);
	traverse(v1);
	
	//swapping two vectors
	v.swap(v1);
	traverse(v);
	traverse(v1);
	
	//insert elements
	v.insert(v.begin(),'5');
	v.insert(v.end(),'x');
	v.insert(v.begin()+2,'1');
	traverse(v);
	
	//insert elements
	v.emplace(v.begin(),'2');
	v.emplace_back('3');
	v.emplace(v.end(),'8');
	traverse(v);
	
	//pointer to array used by vector
	char* p = v.data();
	cout<<"The element at v[2] is : "<<*(p+2)<<endl;
	
	//erase the element
	v.erase(v.begin());
	traverse(v);
	
	//clears the element
	v.clear();
	traverse(v);
	return 0;
}

Output of the above program is

output of the above program. vectors
output of the above program. vectors

Leave a Reply