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