public member function
<iterator>

std::reverse_iterator::operator[]

reference operator[] (difference_type n) const;
/*unspecified*/ operator[] (difference_type n) const;
Dereference iterator with offset
Accesses the element located n positions away from the element currently pointed to by the iterator.

If such an element does not exist, it causes undefined behavior.

Internally, the function accesses the proper element of its base iterator, returning the same as: base()[-n-1].

Parameters

n
Number of elements to offset.
Member type difference_type is an alias of the base iterator's own difference type.

Return value

A reference to the element n positions away from the element currently pointed by the iterator.
Member type reference is an alias of the base iterator's own reference type.
The element n positions away from the element currently pointed by the iterator.
The type corresponds to the one returned by invoking the same operator on the base iterator.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// reverse_iterator::operator[] example
#include <iostream>     // std::cout
#include <iterator>     // std::reverse_iterator
#include <vector>       // std::vector

int main () {
  std::vector<int> myvector;
  for (int i=0; i<10; i++) myvector.push_back(i);  // myvector: 0 1 2 3 4 5 6 7 8 9

  typedef std::vector<int>::iterator iter_type;

  std::reverse_iterator<iter_type> rev_iterator = myvector.rbegin();

  std::cout << "The fourth element from the end is: " << rev_iterator[3] << '\n';

  return 0;
}

Output:

The fourth element from the end is: 6


Data races

The object is accessed.
Depending on the return type, the value returned may be used to access or modify elements.

Exception safety

Provides the same level of guarantee as the operations internally applied to the base iterator.

See also