Forgotten Password?

Or login with:

  • Facebook
  • Google
  • Yahoo

Random Access Iterator

Random access iterator allows you to access elements in any order


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.


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


Example - random access iterator
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.
#include <iostream>
#include <hash_map>
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;

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

Last Modified: 11 Feb 12 @ 12:58     Page Rendered: 2022-03-14 17:40:19