CodeTheRobot

C++ Intermediate · Lesson 08 of 27

Iterators: input, output, forward, bidirectional and random-access

The five iterator categories and what each one allows.

Estimated time · 45–75 min

Learning goals

What you will understand

  • Explain iterators: input, output, forward, bidirectional and random-access in your own words
  • Use it in a small robotics example
  • Verify the result instead of assuming it worked

Understand the idea first

The mental model

An iterator is an object that points into a container and moves through it. begin() points to the first element and end() one past the last. Dereferencing (*it) reads the element and ++it moves to the next.

There are five categories, each adding abilities: input (read once, forward), output (write once, forward), forward (multi-pass), bidirectional (also --it, e.g. std::list and std::map) and random-access (also it + n and it2 - it1, e.g. std::vector and std::array). An algorithm states the category it needs; std::sort needs random access, so it does not work on a std::list.

Guided lesson

Work through these steps

  1. 1.

    Read the iterators: input, output, forward, bidirectional and random-access example and identify what each line owns or changes.

  2. 2.

    Create a small source file, compile with -std=c++17 and warnings enabled, and run it.

  3. 3.

    Change one input, predict the result before running, then compare the output.

  4. 4.

    Record one compiler or runtime error and explain the correction in your own words.

Worked example

Read it before you run it

std::vector<int> v{10, 20, 30, 40};
// A vector supplies random-access iterators.
auto it = v.begin();
// it points at the first element (10).
it += 2;
// Random access: jump two elements ahead in one step.
std::cout << *it << '\n';
// Dereference: prints 30.
std::cout << (v.end() - v.begin()) << '\n';
// Random-access iterators can be subtracted: prints 4, the size.
std::list<int> l{1, 2, 3};
// A list supplies only bidirectional iterators.
auto last = std::prev(l.end());
// prev steps backwards from end() to the final element.
std::cout << *last << '\n';
// Prints 3.
// l.begin() + 2;
// Would not compile: bidirectional iterators cannot jump.

What the example is doing

  1. 1.Read declarations from right to left: identify each value's type, name, and initial value.
  2. 2.Follow the data through each expression before considering syntax shortcuts.
  3. 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.

Watch it run · Values in memory

See what this code does

The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.

motor speed030x1070x1410x1890x1c40x2060x2420x2880x2c*p += 10VALUES IN MEMORY

Demo for Iterators: input, output, forward, bidirectional and random-access. Expected result: 30 4 3

Practice code

Now type it yourself

Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice

#include <iostream>
#include <iterator>
#include <list>
#include <vector>

int main() {
  std::vector<int> v{10, 20, 30, 40};
  std::list<int> l{1, 2, 3};
  // TODO: use random access on v (begin() + 2), then std::prev on the list's end()
  std::cout << *it << '\n' << (v.end() - v.begin()) << '\n' << *last << '\n';
  return 0;
}

Expected output

30
4
3
Stuck? Show the full solution (try it yourself first)
#include <iostream>
#include <iterator>
#include <list>
#include <vector>

int main() {
  std::vector<int> v{10, 20, 30, 40};
  std::list<int> l{1, 2, 3};
  auto it = v.begin() + 2;
  auto last = std::prev(l.end());
  std::cout << *it << '\n' << (v.end() - v.begin()) << '\n' << *last << '\n';
  return 0;
}

Expected result

How you know it worked

  • After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
  • Changing the stated input produces the result you predicted.

Practical exercise

Apply the lesson

Write a function that prints any container with begin()/end(), then try std::sort on a std::vector and a std::list. Read the error for the list and name the missing iterator ability.

Before you continue

  • The program builds with -std=c++17 and no warnings
  • You can explain the key rule without reading the example
  • The normal and edge cases both have recorded results

If something goes wrong

The compiler reports that a name or type is unknown.

Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.

The program runs but the value is wrong.

Print the inputs and intermediate values, then check conversions, units, and collection order.