Traverse in Vectors

We can traverse in vectors using iterators. In this example, we will traverse the elements of vectors using iterators and reverse iterators.

#include<iostream>
#include<vector>
using namespace std;
int main(){
	vector<int> v(5);
	//assigning vector elements
	cout<<"Using for loop "<<endl;
	
	for(int i=0;i<5;++i){
		v[i] = i*2;
	}
	cout<<"The elements of vectors are : "<<endl;
	
	cout<<"Using for loop "<<endl;
	for(int i=0;i<5;i++){
		cout<<v[i]<<" ";
	}
	
	cout<<endl<<"Using iterator "<<endl;
	vector<int>::iterator it;
	for(it=v.begin(); it!=v.end();it++){
		cout<<*it<<" ";
	}

	cout<<endl<<"Using reverse iterator "<<endl;
	vector<int>::reverse_iterator rit;
	for(rit=v.rbegin();rit!=v.rend();rit++){
		cout<<*rit<<" ";
	}
	
	cout<<endl<<"auto type with begin and end"<<endl;
	for(auto i=v.begin();i!=v.end();i++){
		cout<<*i<<" ";
	}
	
	cout<<endl<<"auto type with rbegin and rend"<<endl;
	for(auto i=v.rbegin();i!=v.rend();i++){
		cout<<*i<<" ";
	}
	
	return 0;
}
output of the above program. traverse in vectors
output of the above program. traverse in vectors

Leave a Reply