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 traverse1vector<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 reached4while (it != nums.end()) { // *it dereferences the iterator to get the value5 cout << *it << " "; // Moves to the next element6 ++it;7}// Ends the first line: 10 20 30 40 508cout << endl;9 // Reverse iterators: rbegin() is the last element, and ++ moves toward the front10for (auto rit = nums.rbegin(); rit != nums.rend(); ++rit) { // Prints 50 40 30 20 1011 cout << *rit << " ";12}Output
10 20 30 40 50 50 40 30 20 10
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