C++ Iterators


In C++, an iterator is an object that acts like a pointer used to access elements of containers such as vectors, lists, sets, or maps. Iterators provide a standard way to traverse elements in a container without knowing the underlying structure.

Think of an iterator as a bridge between a container and the algorithm that processes its elements. Instead of directly accessing data using indexes, iterators make it easy to move from one element to another in a uniform manner, regardless of the container type.

Why Use Iterators?

Not all containers in C++ support indexing (like arrays or vectors do). For example, set and map store elements in specific orders but don’t allow direct access through indexes. Iterators solve this problem by providing a universal way to access elements in all STL containers.

Some key advantages of using iterators are:

  • They provide a common way to navigate through different container types.

  • They simplify working with algorithms in the STL (like sort, find, copy, etc.).

  • They make code cleaner and more flexible.

Types of Iterators in C++

C++ supports several types of iterators, each suited for specific use cases:

Type Description
Input Iterator Reads data from a container (one-way traversal).
Output Iterator Writes data to a container (one-way traversal).
Forward Iterator Reads/writes data and allows one-way traversal.
Bidirectional Iterator Can move both forward and backward.
Random Access Iterator Can jump to any element directly (like pointers).

Different STL containers support different types of iterators.
For example:

  • vector and deque support random access iterators.

  • list, set, and map support bidirectional iterators.

Syntax of Iterators

The general syntax for declaring an iterator looks like this:

container_type::iterator iterator_name;

Example:

vector<int>::iterator it;
set<string>::iterator sIt;
map<int, string>::iterator mIt;

Example: Using Iterators with a Vector

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> nums = {10, 20, 30, 40};

    vector<int>::iterator it;
    for (it = nums.begin(); it != nums.end(); ++it) {
        cout << *it << " ";
    }

    return 0;
}

Output:

10 20 30 40

Here, it acts like a pointer. *it accesses the value of the current element.

Example: Using Iterators with a Set

#include <iostream>
#include <set>
using namespace std;

int main() {
    set<string> fruits = {"Apple", "Banana", "Mango"};

    set<string>::iterator it;
    for (it = fruits.begin(); it != fruits.end(); ++it) {
        cout << *it << endl;
    }

    return 0;
}

Output:

Apple
Banana
Mango

Even though a set doesn’t use indexes, iterators make it easy to traverse the elements.

Example: Using Iterators with a Map

#include <iostream>
#include <map>
using namespace std;

int main() {
    map<int, string> students = {{1, "Anita"}, {2, "Pooja"}, {3, "Kavya"}};

    map<int, string>::iterator it;
    for (it = students.begin(); it != students.end(); ++it) {
        cout << it->first << " => " << it->second << endl;
    }

    return 0;
}

Output:

1 => Anita
2 => Pooja
3 => Kavya

In maps, it->first gives the key, and it->second gives the value.

Important Iterator Functions

Function Description
begin() Returns iterator pointing to the first element
end() Returns iterator pointing to past-the-last element
rbegin() Returns reverse iterator to the last element
rend() Returns reverse iterator to before the first element
advance(it, n) Moves iterator n steps forward
next(it) Returns iterator to next position
prev(it) Returns iterator to previous position

Example: Reverse Iterators

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> nums = {1, 2, 3, 4, 5};

    for (vector<int>::reverse_iterator it = nums.rbegin(); it != nums.rend(); ++it) {
        cout << *it << " ";
    }

    return 0;
}

Output:

5 4 3 2 1

Reverse iterators allow you to traverse a container from the end to the beginning.

Example: advance(), next(), and prev()

#include <iostream>
#include <list>
#include <iterator>
using namespace std;

int main() {
    list<int> nums = {10, 20, 30, 40, 50};
    list<int>::iterator it = nums.begin();

    advance(it, 2);  // Move iterator to the third element
    cout << "Element after advancing 2 steps: " << *it << endl;

    auto nextIt = next(it);
    cout << "Next element: " << *nextIt << endl;

    auto prevIt = prev(it);
    cout << "Previous element: " << *prevIt << endl;

    return 0;
}

Output:

Element after advancing 2 steps: 30
Next element: 40
Previous element: 20

Example: Using Iterator with erase()

Iterators are often used to remove elements safely from a container.

#include <iostream>
#include <vector>
using namespace std;

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

    nums.erase(it + 2); // Removes element at index 2

    for (int n : nums)
        cout << n << " ";

    return 0;
}

Output:

1 2 4 5

Summary of the Tutorial

C++ iterators are a powerful feature that allow consistent and efficient traversal through STL containers. They work like pointers and make it easy to manipulate and access container elements, regardless of their type.

Using iterators is especially useful in algorithms like sorting, searching, or modifying data in sets, lists, and maps where indexing isn’t supported. By understanding iterators, you gain full control over how data flows through your programs.


Practice Questions

  1. Write a C++ program to traverse a vector using iterators and display all its elements.

  2. Create a program that uses iterators to display all elements of a set in both normal and reverse order.

  3. Write a C++ program to iterate through a map and print all key-value pairs.

  4. Build a program that finds and removes an element from a list using an iterator.

  5. Write a program to demonstrate the use of advance() function to move an iterator a specific number of positions.

  6. Create a program that finds the largest element in a vector using iterators.

  7. Write a program that reverses the contents of a deque using reverse iterators.

  8. Build a program that prints every alternate element of a vector using iterators.

  9. Write a program to demonstrate the difference between next() and prev() functions in iterators.

  10. Create a C++ program that uses iterators to copy all elements from one container (vector) to another.


Try a Short Quiz.

No quizzes available.


Online Code Editor and Compilor

Write and run code directly in your browser. Live preview for frontend languages.


Go Back Top