Iterator Pattern in C++

Level 5235 keystrokes

Walks through a vector front to back with an explicit iterator and a while loop, then back to front with reverse iterators (rbegin/rend).

C++ code

// Five numbers to traverse
1vector<int> nums = {10, 20, 30, 40, 50};
2
// Iterator pointing to the first element (type written out explicitly)
3vector<int>::iterator it = nums.begin();
// end() points one past the last element, so loop until it is reached
4while (it != nums.end()) {
// *it dereferences the iterator to get the value
5 cout << *it << " ";
// Moves to the next element
6 ++it;
7}
// Ends the first line: 10 20 30 40 50
8cout << endl;
9
// Reverse iterators: rbegin() is the last element, and ++ moves toward the front
10for (auto rit = nums.rbegin(); rit != nums.rend(); ++rit) {
// Prints 50 40 30 20 10
11 cout << *rit << " ";
12}

Output

10 20 30 40 50 
50 40 30 20 10 
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 12
  • ;× 8
  • (× 6
  • )× 6
  • =× 5
  • ,× 4
  • .× 4
  • "× 4
  • +× 4
  • {× 3

More C++ examples at level 5

← C++ typing practice