Iterators

From Rosetta Code
Revision as of 07:05, 24 January 2022 by Garbanzo (talk | contribs) (Create Iterators task)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Iterators is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Iterators are a design pattern that can be used to access elements of a container without depending on the implementation or type of the container.

Task
  • Create an array like container to hold the days of the week and a linked-list like container to hold colors.
  • Print all of the elements of each container.
  • Print the first, fourth, and fifth elements of each container.
  • Print the last, fourth to last, and fifth to last of each container.


If you language supports iterators, use them. Otherwise show how access to elements can be separated from the containers that hold them.

C++

<lang cpp>#include <iostream>

  1. include <list>
  2. include <string>
  3. include <vector>

using namespace std;

// Use iterators to print all of the elements of any container that supports // iterators. It print elements starting at 'start' up to, but not // including, 'sentinel'. void PrintContainer(forward_iterator auto start, forward_iterator auto sentinel) {

 for(auto it = start; it != sentinel; ++it)
 {
   cout << *it << " "; 
 }
 cout << "\n";

}

// Use an iterator to print the first, fourth, and fifth elements void FirstFourthFifth(input_iterator auto it) {

 cout << *it;
 advance(it, 3);
 cout << ", " << *it;
 advance(it, 1);
 cout << ", " << *it;
 cout << "\n";

}

int main() {

 // Create two differnt kinds of containers of strings
 vector<string> days{"Sunday", "Monday", "Tuesday", "Wednesday",
  "Thursday", "Friday", "Saturday"};
 list<string> colors{"Red", "Orange", "Yellow", "Green", "Blue", "Purple"};
 cout << "All elements:\n";
 PrintContainer(days.begin(), days.end());
 PrintContainer(colors.begin(), colors.end());
 
 cout << "\nFirst, fourth, and fifth elements:\n";
 FirstFourthFifth(days.begin());
 FirstFourthFifth(colors.begin());
 cout << "\nReverse first, fourth, and fifth elements:\n";
 FirstFourthFifth(days.rbegin());
 FirstFourthFifth(colors.rbegin());

} </lang>

Output:
All elements:
Sunday Monday Tuesday Wednesday Thursday Friday Saturday 
Red Orange Yellow Green Blue Purple 

First, fourth, and fifth elements:
Sunday, Wednesday, Thursday
Red, Green, Blue

Reverse first, fourth, and fifth elements:
Saturday, Wednesday, Tuesday
Purple, Yellow, Orange