Custom Iterator in C++

Level 5510 keystrokes

Range provides begin() and end() returning a small nested Iterator with *, ++ and !=, which is all a range-based for loop needs. Range(1, 6) yields 1 to 5 (the end value is excluded).

C++ code

// A range of integers from start_ up to (not including) end_
1class Range {
2 int start_, end_;
3public:
4 Range(int s, int e) : start_(s), end_(e) {}
5
// Nested iterator class that only stores the current value
6 class Iterator {
7 int current_;
8 public:
9 Iterator(int val) : current_(val) {}
// * returns the current value
10 int operator*() const { return current_; }
// Prefix ++ moves to the next value
11 Iterator& operator++() { ++current_; return *this; }
// != tells the loop when to stop
12 bool operator!=(const Iterator& other) const { return current_ != other.current_; }
13 };
14
// begin() and end() are what a range-based for loop calls
15 Iterator begin() const { return Iterator(start_); }
16 Iterator end() const { return Iterator(end_); }
17};
18
// Iterates from 1 while the value is != 6
19for (int n : Range(1, 6)) {
// Prints 1 2 3 4 5
20 cout << n << " ";
21}
22cout << endl;

Output

1 2 3 4 5
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.

  • (× 14
  • )× 14
  • _× 12
  • ;× 12
  • {× 10
  • }× 10
  • <× 6
  • :× 5
  • ,× 4
  • +× 4

More C++ examples at level 5

← C++ typing practice