void shrink_to_fit(); // (1) C++11
constexpr void shrink_to_fit(); // (1) C++20
概要
領域をコンテナのサイズまで切り詰める
要件
- C++14 : 型
T
が*this
に対してムーブ挿入可能であること
効果
capacity()
をsize()
に縮小させるというリクエストを行う。- 実装依存の最適化を許可するために、縮小するという動作は仕様上強制されない。
- C++17 : この関数によって
capacity()
が増えることはない。 - C++17 :
capacity()
の縮小が起こる際に、メモリの再割り当てが発生する場合がある。その際、コンテナの要素に対する参照、ポインタ、およびイテレータとそれが指す要素への参照は無効となる。 - C++14 : コピー挿入可能でない型
T
のムーブコンストラクタによる例外を除き、例外が送出された場合この関数は何もしない。
戻り値
なし
計算量
- C++14 : 最大で、要素数に対して線形時間
例
#include <iostream>
#include <vector>
#include <cassert>
int main()
{
std::vector<int> v = {1, 2, 3};
std::cout << v.capacity() << std::endl;
// 要素削除 : capacityは減らない
v.erase(v.begin());
std::cout << v.capacity() << std::endl;
// 領域を切り詰める
v.shrink_to_fit();
std::cout << v.capacity() << std::endl;
assert(v.capacity() == v.size());
}
xxxxxxxxxx
#include <iostream>
#include <vector>
#include <cassert>
int main()
{
std::vector<int> v = {1, 2, 3};
std::cout << v.capacity() << std::endl;
// 要素削除 : capacityは減らない
v.erase(v.begin());
std::cout << v.capacity() << std::endl;
// 領域を切り詰める
v.shrink_to_fit();
std::cout << v.capacity() << std::endl;
assert(v.capacity() == v.size());
}
出力
3
3
2
バージョン
言語
- C++11
処理系
- Clang: ??
- GCC: 4.6.1 ✅
- ICC: ??
- Visual C++: 2010 ✅, 2012 ✅, 2013 ✅
参照
- 『Effective STL - STLを効果的に使いこなす50の鉄則』 第17項 余分な容量を取り除くには「swap技法」を使おう
- LWG Issue 755.
std::vector
andstd:string
lack explicit shrink-to-fit operations - LWG Issue 2033. Preconditions of
reserve
,shrink_to_fit
, andresize
functions - LWG Issue 2223.
shrink_to_fit
effect on iterator validity - P1004R2 Making
std::vector
constexpr