C++_Primer chapter9 3.顺序容器的操作

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值