C++11:shrink_to_fit的基本作用与使用

vector::shrink_to_fit() 是 C++ STL 中的内置函数,它减少容器的容量以适应其大小并销毁超出容量的所有元素。

#include <iostream>
#include <vector>
using namespace std;

int main()
{
	vector<int> v(10);

	for (int i = 0; i < 10; i++)
		v[i] = i;

	cout << "Vector size initially: " << v.size();

	cout << "\nVector elements are: ";
	for (int i = 0; i < 10; i++)
		cout << v[i] << " ";

	v.resize(5);//size置为5,capacity不变

	cout << "\n\nVector size after resize(5): "
		<< v.size();

	cout << "\nVector elements after resize(5) are: ";
	for (int i = 0; i < 10; i++)
		cout << v[i] << " ";    //输出后五个数是之前初始化过的数

	v.shrink_to_fit();//capacity置为size大小5

	cout << "\n\nVector size after shrink_to_fit(): "
		<< v.size();

	cout << "\nVector elements after shrink_to_fit() are: ";
	for (int i = 0; i < 10; i++)
		cout << v[i] << " ";    //输出后五个数是不可预料的大小,因为已经销毁

	return 0;
}

运行结果:

Vector size initially: 10
Vector elements are: 0 1 2 3 4 5 6 7 8 9

Vector size after resize(5): 5
Vector elements after resize(5) are: 0 1 2 3 4 5 6 7 8 9

Vector size after shrink_to_fit(): 5
Vector elements after shrink_to_fit() are: 0 1 2 3 4 -1 -1755884051 134230871 0 2
Process returned 0 (0x0)   execution time : 0.033 s
Press any key to continue.

IDE:Code::Blocks

编译器:g++(-std=c++20)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值