可使用reserve(int len)函数为容器预留len个元素长度,这样做可减少vector在动态扩展容量时的扩展次数。
预留位置不初始化,元素不可访问。
#include<iostream>
using namespace std;
#include<vector>
int main()
{
vector<int> v;
v.reserve(10);
cout << "capacity: " << v.capacity() << endl;
cout << "size: " << v.size() << endl;
system("pause");
}
运行结果:
capacity: 10
size: 0
请按任意键继续. . .