How to Write an STL Iterator

104 30
    • 1). Load the C++ IDE by clicking on its program icon. When it opens, select "File/New/Project" and choose "C++ Project" to create a new C++ project. A blank source code file appears in the text editor portion of the IDE.

    • 2). Include the libraries "iostream," "list," and "iterator" by writing the following statements at the top of the source code file:

      #include <iostream>

      #include <list>

      #include <iterator>

      using namespace std;

    • 3). Declare a main function by writing the following line of code:

      int main () {}

    • 4). Create a new list by writing the following statement between the curly brackets of the main function:

      list<int> aList;

    • 5). Fill the list with a few items using the push_back function. Write the following statements beneath the statement written in the previous step:

      aList.push_back(1);

      aList.push_back((2);

      aList.push_back(3);

    • 6). Create an iterator to the list by writing the following statement below the previous statement:

      list<int>::iterator aListIter;

    • 7). Iterate through the list using a "for" loop. With the help of the "for" loop, the iterator will traverse the list. Write the following "for" loop below the previous statement:

      for(i = aList.begin(); i!= aList.end(); ++i){}

    • 8). Output the contents of the element to which the iterator is currently pointing. By using the * operator on the iterator, you can write its value to the console output, cout. Write the following within the curly brackets of the "for" loop to write out the iterator's contents.

      cout << *i << endl;

    • 9). Execute the program by pressing the green arrow button located on the top row of buttons in the IDE. The program will create a list, populate it with a few items, and then iterate through the list with an iterator. The iterator writes out each item to which it points. The output looks like this:

      1

      2

      3

Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.