Random access iterator allows you to access elements in any order

View versions (1)

Description

Random access iterator allows the access to elements in any order, may store and retrieve values, provided by vector, deque, string, and array.

Random Access Iterators provide essentially all of the operations of ordinary C pointer arithmetic.

Operations

ExpressionDescription
i[n]Provides access to the element that has index n
i+=nSteps n elements forward (or backward, if n is negative)
i-=nSteps n elements backward (or forward, if n is negative)
i+nReturns the iterator of the nth next element
n+iReturns the iterator of the nth next element
i-nReturns the iterator of the nth previous element
i1-i2Returns the distance between i1 and i2
i1<i2Returns if i1 is before i2
i1>i2Returns if i1 is after i2
i1<=i2Returns if i1 is not after i2
i1>=i2Returns if i1 is not before i2

References

Example 1
Problem

This program illustrates a hash_map including a default constructor and the insert(), begin(), erase() member functions of the STL hash_map interface using random access iterator.

Workings
#include <iostream>
#include <hash_map>
#define _DEFINE_DEPRECATED_HASH_CLASSES 0
typedef pair <int, int> Int_Pair;

using namespace std;
using namespace stdext;

int main()
{
  hash_map <int, int> hm1;
  hash_map <int, int> :: iterator hm1_Iter;
  hash_map <int, int> :: const_iterator hm1_cIter;

  hm1.insert (Int_Pair(0, 0));
  hm1.insert (Int_Pair(1, 1));
  hm1.insert (Int_Pair(2, 4));
  
  hm1_cIter = hm1.begin ( );
  cout <<"The first element of hm1 is "<<hm1_cIter -> first<<"."<<endl;

  hm1_Iter = hm1.begin ( );
  hm1.erase ( hm1_Iter );

  // The following 2 lines would err because the iterator is const
  // hm1_cIter = hm1.begin ( );
  // hm1.erase ( hm1_cIter );

   hm1_cIter = hm1.begin( );
   cout <<"The first element of hm1 is now "<<hm1_cIter -> first<<"."<<endl;

  return 0;
}
Solution

Output:

The first element of hm1 is 0.
The first element of hm1 is now 1.

See Also