1、swap可以使两个容器互换,可以达到实用的收缩内存效果
2、预留空间可以减少vector在动态扩展容量时的扩展次数如果数据量较大,可以一开始利用reserve预留空间
#include<iostream>
#include <string>
#include <vector>
using namespace std;
void printfVector(vector<int>& v)
{
for (vector<int>::iterator it = v.begin();it != v.end();it++)
{
cout << *it << " ";
}
cout << endl;
}
void test01()
{
vector<int> v;
for (int i = 0;i < 10;i++)
{
v.push_back(i);
}
printfVector(v);
vector<int> v2;
for (int i = 10;i > 0;i--)
{
v2.push_back(i);
}
printfVector(v2);
v.swap(v2);
printfVector(v);
printfVector(v2);
}
void test02()
{
vector<int> v1;
for (int i = 0;i < 1000000;i++)
{
v1.push_back(i);
}
cout << "v1的容量:"<< v1.capacity() << endl;
cout << "v1的大小:" << v1.size() << endl;
v1.resize(10);
cout << "v1的容量:" << v1.capacity() << endl;
cout << "v1的大小:" << v1.size() << endl;
vector<int>(v1).swap(v1);
cout << "v1的容量:" << v1.capacity() << endl;
cout << "v1的大小:" << v1.size() << endl;
}
void test03()
{
int num = 0;
int* p = NULL;
vector<int> v;
v.reserve(1000000);
for (int i = 0;i < 1000000;i++)
{
v.push_back(i);
if (p != &v[0])
{
p = &v[0];
num++;
}
}
cout << num << endl;
}
int main()
{
test03();
return 0;
}
|