Iterators in C++

Lesson Introduction

Welcome to the world of iterators in C++! Iterators are fundamental to the C++ Standard Library, enabling efficient traversal and manipulation of container elements. The goal of this lesson is to help you understand what iterators are, how to use them effectively, and why they are essential.

By the end of this lesson, you'll know how to declare and use iterators to traverse and modify elements in a std::vector.

Basic Concept of Iterators and Types of Iterators

So, what exactly is an iterator? An iterator is an object that lets you access elements in a container (such as std::vector, std::list, etc.) sequentially without exposing the container's underlying representation.

There are several types of iterators in C++:

  • Input Iterators: Read-only access to elements.
  • Output Iterators: Write-only access to elements.
  • Forward Iterators: Read and write access, single-pass.
  • Bidirectional Iterators: Read and write access, and can move both forward and backward.
  • Random-Access Iterators: Read and write access, and can move to any element in constant time.

For this lesson, we will focus on Random-Access Iterators, typically used with std::vector.

Traversing Elements Using an Iterator

To iterate over the elements of a vector, we use the begin() and end() member functions:

  • begin(): Returns an iterator to the first element of the container.
  • end(): Returns an iterator to just past the last element of the container.

An iterator can be incremented, decremented, and dereferenced. Let's break this down:

  • Increment: Moves the iterator to the next element.
  • Decrement: Moves the iterator to the previous element.
  • Dereference: Accesses the value the iterator points to.

Remember, the dereference operator (*) is used to obtain the value that the iterator points to, much like how you dereference pointers.

C++
#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    std::vector<int>::iterator it;

    // Incrementing and dereferencing the iterator
    it = numbers.begin();
    std::cout << *it << std::endl; // Output: 1

    ++it;
    std::cout << *it << std::endl; // Output: 2

    return 0;
}

In this snippet, we initialize it to the beginning of the vector and increment it to access the second element. Note that:

  • the iterator has type <data type>::iterator
  • we dereference the iterator with *, like a pointer.
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal