vector容器互换容器(7)

功能描述:

  • 实现两个容器内元素进行互换

函数原型:

swap(ve

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 
 5 void printVector(vector<int> &v)
 6 {
 7     for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
 8     {
 9         cout << *it << " ";
10     }
11     cout << endl;
12 }
13 
14 void test_01()
15 {
16     vector<int> v1;
17     for (int i = 0; i < 10;i++)
18     {
19         v1.push_back(i);
20     }
21     printVector(v1);
22 
23     vector<int> v2;
24     for (int i = 10; i > 0; i--)
25     {
26         v2.push_back(i);
27     }
28     printVector(v2);
29 
30     cout << "交换后:" << endl;
31     v1.swap(v2);
32     printVector(v1);
33     printVector(v2);
34 
35 }
36 
37 //实际用途
38 void test_02()
39 {
40     vector<int> v;
41     for (int i = 0; i < 100000; i++)
42     {
43         v.push_back(i);
44     }
45 
46     cout << "容量:" << v.capacity() << endl;
47     cout << "大小:" << v.size() << endl;
48 
49     //重新指定大小
50     v.resize(3);
51     cout << "容量:" << v.capacity() << endl;
52     cout << "大小:" << v.size() << endl;
53 
54     //巧用.swap来收缩内存
55     vector<int>(v).swap(v);//vector<int>(v)匿名对象,
56     cout << "容量:" << v.capacity() << endl;
57     cout << "大小:" << v.size() << endl;
58 }
59 
60 int main(void)
61 {
62     //test_01();
63 
64     test_02();
65 
66     system("pause");
67     return 0;
68 
69 }

 

 

c); // 将vec与本身的元素互换

posted @ 2020-07-10 13:15  坦率  阅读(432)  评论(0编辑  收藏  举报