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 value6 class Iterator {7 int current_;8 public:9 Iterator(int val) : current_(val) {} // * returns the current value10 int operator*() const { return current_; } // Prefix ++ moves to the next value11 Iterator& operator++() { ++current_; return *this; } // != tells the loop when to stop12 bool operator!=(const Iterator& other) const { return current_ != other.current_; }13 };14 // begin() and end() are what a range-based for loop calls15 Iterator begin() const { return Iterator(start_); }16 Iterator end() const { return Iterator(end_); }17};18 // Iterates from 1 while the value is != 619for (int n : Range(1, 6)) { // Prints 1 2 3 4 520 cout << n << " ";21}22cout << endl;Output
1 2 3 4 5
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