vector里的resize() & reserve()

2 篇文章 0 订阅

直接贴代码:

#include <vector>
#include <iostream>
using std::cout;
using std::endl;
using std::vector;

int main()
{
	int a[] = { 2,4,5,5,5,1,8,7,4 };
	vector<int> test(a, a + 9);
	vector<int>::iterator it, it1;
	cout << test.size() << "  " << test.capacity() <<endl<<endl;  //分别输出容器的元素个数和容量(及可容纳元素个数)
	for (it = test.begin(); it != test.end();)
	{
		it1 = find(test.begin(), it, *it);    //若当前位置之前存在重复元素,删除当前元素,erase返回当前元素的下一个元素指针
		if (it1 != it)
			it = test.erase(it);
		else
			it++;
	}
	cout << "result: " << endl;
	for (it = test.begin(); it<test.end(); it++)
		cout << *it;
	cout << endl << endl;

	cout << test.size() << "  " << test.capacity() << endl;  //只改变size,不改变capacity,即只改变元素个数,不改变容量

	test.reserve(7);  //强制改变容器的容量,但7<9,编译器会忽略
	cout << test.size() << "  " << test.capacity() << endl;
	for (it = test.begin(); it<test.end(); it++)
		cout << *it;
	cout << endl << endl;

	test.reserve(12); //12>9,强制改变容器容量为12
	cout << test.size() << "  " << test.capacity() << endl;
	for (it = test.begin(); it<test.end(); it++)
		cout << *it;
	cout << endl << endl;

	test.resize(3);   //强制改变元素个数,因为3<12(容量),所以容量不会改变(还装得下),元素保留前3个
	cout << test.size() << "  " << test.capacity() << endl;  
	for (it = test.begin(); it<test.end(); it++)
		cout << *it;
	cout << endl << endl;

	test.resize(7);   //7<12,容量仍旧不会改变,元素增加,默认补0
	cout << test.size() << "  " << test.capacity() << endl;  
	for (it = test.begin(); it<test.end(); it++)
		cout << *it;
	cout << endl << endl;

	test.resize(9, 2);//9<12,容量不变,元素增加,元素为2,resize()的重载
	cout << test.size() << "  " << test.capacity() << endl;
	for (it = test.begin(); it<test.end(); it++)
		cout << *it;
	cout << endl << endl;

	test.resize(15);  //因为15>12,容器装不下了,所以容量会自动分配
	cout << test.size() << "  " << test.capacity() << endl;  
	for (it = test.begin(); it<test.end(); it++)
		cout << *it;
	cout << endl << endl;
	
	system("pause");
}

运行结果:

在这里插入图片描述
萌新一枚,还望各路大神指点=。=

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值