#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec(20, 1);
cout << vec.capacity() << endl; // print 20
cout << vec.size() << endl; // print 20
vec.reserve(100); // 预留空间
cout << vec.capacity() << endl; // print 100
cout << vec.size() << endl; // print 20
/*
* 如果n比当前的vector元素数目要小,vector的容量要缩减到resize的第一个参数大小,既n。
* 并移除那些超出n的元素同时销毁他们。
* 如果n比当前vector元素数目要大,在vector的末尾扩展需要的元素数目,
* 如果第二个参数val指定了,扩展的新元素初始化为val的副本,否则按类型默认初始化
*/
vec.resize(10,0); // n = 10 ,不能指定 0到9位置的元素值
cout << vec.capacity() << endl; // print 100
cout << vec.size() << endl; // print 10
cout << vec[0] << endl; // print 1, not 0
return 0;
}
C++_Primer chapter9 3.顺序容器的操作
最新推荐文章于 2020-12-14 20:57:48 发布