Library contents

C++ Vector reverse iterators

Read an ordered receipt history from the most recent entry to the earliest.

A simple example

Vector reverse iterators

  1. Start with A, B, C
  2. Do this Read in reverse order
  3. Result C, B, A
Starting at the last item reverses the order of the three values.

Syntax

C++ syntax
receipts.rbegin()
Run these examples in C++

Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.

c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson

Read a receipt history newest first

A shop archives receipts in the order they were issued. The returns counter needs the newest receipt at the top of its screen without rearranging the archive for the accounting team.

ResultR3, R2, R1
lesson.cpp
#include <iostream>
#include <vector>
#include <string>

int main() {
    std::vector<std::string> receipts{"R1", "R2", "R3"};
    for (auto it = receipts.rbegin(); it != receipts.rend(); ++it) {
        std::cout << (it == receipts.rbegin() ? "" : ", ") << *it;
    }
    return 0;
}
Output
R3, R2, R1

The counter sees receipt R3 first and R1 last.

Advertisements

Prepare the next workshop roster

A teacher reads a workshop roster in arrival order. The coordinator needs to visit the entries in reverse order on the return trip. Read the order from the final entry back to the first.

GivenMira · Ivo · Bea
Worked resultBea · Ivo · Mira

Work from the delivery round

A courier has three labelled stops in route order. The coordinator needs to visit the entries in reverse order on the return trip. Read the order from the final entry back to the first.

GivenPark · Mill · Pier
Worked resultPier · Mill · Park

What to watch for

Reverse iterators traverse existing storage. Keep the vector alive and avoid invalidating iterators during traversal.

Documentation for Vector reverse iterators