/
Collections and Iterators
Collections and Iterators
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;
// This next line is crazy, don't do it...
auto pos2 = distance(iter1, iter2);
cout << "distance between iter1.end and iter2.end: " << pos2 << endl;
return 0;
}