-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path18_vector_互换容器.cpp
69 lines (58 loc) · 1.25 KB
/
18_vector_互换容器.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
#include <vector>
using namespace std;
// vector 互换容器
// swap(vec); // 将vec与本身的元素互换
void printVector(vector<int> &v)
{
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
// 基本使用
void test01()
{
vector<int> v1;
for (int i = 0; i < 10; i++)
{
v1.push_back(i);
}
printVector(v1);
vector<int> v2;
for (int i = 9; i >= 0; i--)
{
v2.push_back(i);
}
printVector(v2);
// 交换
v1.swap(v2);
printVector(v1);
printVector(v2);
}
// 实际用途:巧用swap可以收缩内存空间
void test02()
{
vector<int> v;
for (int i = 0; i < 100000; i++)
{
v.push_back(i);
}
cout << "v 容量为 " << v.capacity() << endl;
cout << "v 大小为 " << v.size() << endl;
v.resize(3);
cout << "v 容量为 " << v.capacity() << endl;
cout << "v 大小为 " << v.size() << endl;
// 巧用swap收缩内存
vector<int>(v).swap(v);
// vector<int>(v) 匿名对象,拷贝构造
cout << "v 容量为 " << v.capacity() << endl;
cout << "v 大小为 " << v.size() << endl;
}
int main()
{
// test01();
test02();
return 0;
}