跳到正文

休闲·娱乐

【随笔】vector 相关:shrink_to_fit

ducati约 2 分钟
原文
文章信息与版本

文章信息

发布
2024年3月7日
收录
2025年12月12日
更新
2026年11月16日
篇幅
约 2 分钟

版本

  1. v1当前

在 U 群看到大家在讨论 shrink_to_fit,于是就有了这篇文章。

根据 cppreference,shrink_to_fit 的本质是,释放 vector 的一部分内存,将 capacity() 缩减到 size()。

C++
// from cppreference
Requests the removal of unused capacity.
It is a non-binding request to reduce capacity() to size(). It depends on the implementation whether the request is fulfilled.

而 vector 在每次 emplace_back 之后可能 realloc,导致 capacity() 成倍增长。

如果混用 emplace_back 和 shrink_to_fit,极端情况会发生什么事情呢?

  • 每次 emplace_back 后,capacity() 成倍增长。
  • 每次 shrink_to_fit 后,capacity() 变回 size()。
  • 以上过程可能不断循环。

为进一步验证,写出如下代码:

C++
// test_memory.cpp
#include <bits/stdc++.h>
using namespace std;

vector<int> vec((1 << 24) - 1, 1);
int main() {
	for (int t = 1; t <= 1000; t++) {
		vec.emplace_back(1);
		vec.shrink_to_fit();
	}
	return 0;
}

先注释第八行,再取消注释,测试结果如下:

预料之中。


记得去年某场模拟赛,我和大家做法都差不多,大家没怎么卡常就过了,我死活卡不过去,比赛最后时刻把 shrink_to_fit 去了就过了,而且跑得飞快。这给我留下了相当大的心理阴影,从此再也没有用过 shrink_to_fit。

那么 shrink_to_fit 在 OI 里有什么用呢?本质是牺牲一定的时间换取空间,但大命题趋势是卡时间不卡空间(特例除外),所以我认为 shrink_to_fit 在 OI 里几乎没有任何价值。

原文
存档评论8 条抓取于