Fish Touching🐟🎣

C++ Iterator

Apr 3, 2023

Used in C++ STL
Source

# What

An iterator is an object (like a pointer) that points to an element inside the container.
The C++ Standard Library containers all provide iterators so that algorithms can access their elements in a standard way without having to be concerned with the type of container the elements are stored in.
You can use iterators explicitly using member and global functions such as begin() and end() and operators such as ++ and -- to move forward or backward. You can also use iterators implicitly with a range-for loop or (for some iterator types) the subscript operator [].

vector<int> vec{ 0,1,2,3,4 };
for (auto it = begin(vec); it != end(vec); it++)
{
    // Access element using dereference operator
    cout << *it << " ";
}

There are five categories of iterators. In order of increasing power, the categories are:

# How to Use

  1. begin(): The begin() function is a member function of the C++ containers such as vector, list, etc., that returns an iterator pointing to the first element in the container.
  2. end(): Member function of the C++ Iterator class which returns an iterator pointing to the past-the-end element of a container. It compares equal to the result of the last incrementing operator for any valid iterator range in this container. If the container is empty, then end() points to the same position as begin().
  3. advance() : advance() is a method used to increment an iterator given the number of elements it should be advanced by. It takes distance as argument and returns nothing. It’s defined in the <iterator> header.
  4. next(): The next() method returns the next element in the sequence.
  5. prev(): Opposite of next()
  6. inserter(): It takes a container and an iterator as arguments and returns an iterator that can be used to insert elements into the container. The returned iterator is an insert_iterator, which allows elements to be inserted into the container using operator* and operator++. This is useful for cases where elements need to be inserted into a particular position in the container, such as when merging two sorted lists.