Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

A simple vector and examining its iterators

// iterators.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

// C++ program to illustrate the 
// iterators in vector 
#include <iostream> 
#include <vector> 

using namespace std;

int main()
{
	vector<int> g1;
	vector<int> g2;

	for (int i = 1; i <= 5; i++)
	{
		g1.push_back(i);
		g2.push_back(i);
	}

	cout << "Output of begin and end: ";
	for (auto i = g1.begin(); i != g1.end(); ++i)
		cout << *i << " ";

	cout << "\nOutput of cbegin and cend: ";
	for (auto i = g1.cbegin(); i != g1.cend(); ++i)
		cout << *i << " ";

	cout << "\nOutput of rbegin and rend: ";
	for (auto ir = g1.rbegin(); ir != g1.rend(); ++ir)
		cout << *ir << " ";

	cout << "\nOutput of crbegin and crend : ";
	for (auto ir = g1.crbegin(); ir != g1.crend(); ++ir)
		cout << *ir << " ";

	cout << endl;

	// collection.end() points to the theoretical end, an address somewhere
	// on checking both collections g1 and g2, point to the same end but have different starts
	auto iter1 = g1.end();
	auto iter2 = g2.end();
	auto start1 = g1.begin();
	auto start2 = g2.begin();
	auto pos1 = distance(g1.begin(), iter1);
	cout << "distance between iterator 1 start and end: " << pos1 << endl;
	auto pos2 = distance(iter1, iter2);
	cout << "distance between iter1.end and iter2.end: " << pos2 << endl;


	return 0;
}
  • No labels