1: //vector14.cpp
3: #include <iostream>
4: #include <string>
5: #include <vector>
6: using namespace std;
8: int main()
9: {
10: cout << "\nThis program illustrates the swap() member function "
11: "for vector objects.";
12: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
14: vector<int> v1(5, 5);
15: cout << "\nFor v1 we have:";
16: cout << "\nSize = " << v1.size() << " Capacity = " << v1.capacity();
17: cout << "\nContents: ";
18: for(vector<int>::size_type i=0; i<v1.size(); i++)
19: cout << v1.at(i) << " ";
20: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
22: vector<int> v2(10, 10);
23: cout << "\nFor v2 we have:";
24: cout << "\nSize = " << v2.size() << " Capacity = " << v2.capacity();
25: cout << "\nContents: ";
26: for(vector<int>::size_type i=0; i<v2.size(); i++)
27: cout << v2.at(i) << " ";
28: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
30: cout << "\nNow we swap v1 and v2 with v1.swap(v2) and redisplay.";
31: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
33: v1.swap(v2);
34: cout << "\nFor v1 we have:";
35: cout << "\nSize = " << v1.size() << " Capacity = " << v1.capacity();
36: cout << "\nContents: ";
37: for(vector<int>::size_type i=0; i<v1.size(); i++)
38: cout << v1.at(i) << " ";
39: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
40: cout << "\nFor v2 we have:";
41: cout << "\nSize = " << v2.size() << " Capacity = " << v2.capacity();
42: cout << "\nContents: ";
43: for(vector<int>::size_type i=0; i<v2.size(); i++)
44: cout << v2.at(i) << " ";
45: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
47: cout << "\nNow we change the capacities and swap again with the "
48: "following code sequence\nto observe how the capacities are "
49: "\"carried along\" during the swap:"
50: "\nv1.reserve(12);"
51: "\nv2.reserve(7);"
52: "\nv2.swap(v1);";
53: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
55: v1.reserve(12);
56: v2.reserve(7);
57: v2.swap(v1);
58: cout << "\nFor v1 we have:";
59: cout << "\nSize = " << v1.size() << " Capacity = " << v1.capacity();
60: cout << "\nContents: ";
61: for(vector<int>::size_type i=0; i<v1.size(); i++)
62: cout << v1.at(i) << " ";
63: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
64: cout << "\nFor v2 we have:";
65: cout << "\nSize = " << v2.size() << " Capacity = " << v2.capacity();
66: cout << "\nContents: ";
67: for(vector<int>::size_type i=0; i<v2.size(); i++)
68: cout << v2.at(i) << " ";
69: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
70: }