Iterator

An iterator is a variable that points to an element in a data structure.

We often use the begin() and end() iterators define a range that contains all elements in a data structure

  • begin points to the first element in the data structure
  • IMPORTANT: end points to the position after the last element

iterator

std::vector<int>::iterator it;

Examples

Using C++ Iterator
sort(v.begin(), v.end());
reverse(v.begin(), v.end());
random_shuffle(v.begin(), v.end());
set::iterator it = s.begin();
// OR Simpler/Shorter
auto it = s.begin();

The element to which an iterator points can be accessed using the * symbol. For example, the following code prints the first element in the set:

auto it = s.begin(); 
cout << *it << "\n"; 

Iterators can be moved using the operators ++ (forward) and — (backward).

//Prints all the elements in increasing order using iterator
for (auto it = s.begin(); it != s.end(); it++) { cout << *it << "\n"; } 

The following code prints the largest element in the set:

auto it = s.end(); 
it--; 
cout << *it << "\n";

If you want to better see how to implement your own iterators as learned in CS247, see Iterator Design Pattern.