1: //list05.cpp
3: #include <iostream>
4: #include <string>
5: #include <list>
6: using namespace std;
8: int main()
9: {
10: cout << "\nThis program illustrates typical uses of the "
11: "default list class iterator\n(which is a bidirectional "
12: "iterator), and shows the use of operators =, ++,\n--, "
13: "!= and * with list class iterators..";
14: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
16: list<int> lst1(8);
18: cout << "\nFirst we enter some integer squares into "
19: "a list of size 8, and then display: \n";
20: //Create and initialize an iterator.
21: list<int>::iterator p = lst1.begin();
22: int i = 0;
23: while(p != lst1.end())
24: {
25: *p = i*i; //Assign i*i to list lst via iterator p.
26: p++; //Advance the iterator **after** using it.
27: i++; //Increment the value to be squared.
28: }
29: p = lst1.begin();
30: while(p != lst1.end()) cout << *p++ << " ";
31: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
33: cout << "\nNext we double the values in the list and "
34: "re-display (backwards this time): \n";
35: p = lst1.begin();
36: while(p != lst1.end())
37: {
38: *p = *p * 2;
39: p++;
40: }
41: //This time, initialize the iterator to lst1.end().
42: //And decrement the iterator **before** using it!
43: p = lst1.end();
44: while(p != lst1.begin()) cout << *--p << " "; //Note *--p "idiom".
45: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
46: }