Namespaces
Variants

std::deque<T,Allocator>:: shrink_to_fit

From cppreference.net

void shrink_to_fit ( ) ;
(constexpr C++26以降)

未使用の容量の削除を要求します。

これは、シーケンスのサイズを変更せずにメモリ使用量を削減する非拘束的な要求です。要求が満たされるかどうかは実装に依存します。

すべてのイテレータ( end() イテレータを含む)および要素へのすべての参照は無効になります。

T MoveInsertable でない場合、 std:: deque < T, Allocator > への動作は未定義です。

(C++11以降)

目次

翻訳のポイント: - 「Contents」→「目次」に翻訳 - C++関連の専門用語(Complexity、Exceptions、Notes、Example、Defect reports、See also)は原文のまま保持 - HTMLタグ、属性、クラス名は一切変更せず - 数値、構造、書式は完全に維持 - プロフェッショナルな技術文書としての正確性を確保

計算量

コンテナのサイズに対して最大でも線形時間。

例外

CopyInsertable でない T のムーブコンストラクタ以外によって例外がスローされた場合、効果はない。

(C++11以降)

注記

libstdc++では、 shrink_to_fit() C++98モードでは利用できません

#include <cstddef>
#include <deque>
#include <iostream>
#include <new>
// デバッグ出力付き最小限のC++11アロケータ
template<class Tp>
struct NAlloc
{
    typedef Tp value_type;
    NAlloc() = default;
    template<class T> NAlloc(const NAlloc<T>&) {}
    Tp* allocate(std::size_t n)
    {
        n *= sizeof(Tp);
        std::cout << "allocating " << n << " bytes\n";
        return static_cast<Tp*>(::operator new(n));
    }
    void deallocate(Tp* p, std::size_t n)
    {
        std::cout << "deallocating " << n*sizeof*p << " bytes\n";
        ::operator delete(p);
    }
};
template<class T, class U>
bool operator==(const NAlloc<T>&, const NAlloc<U>&) { return true; }
template<class T, class U>
bool operator!=(const NAlloc<T>&, const NAlloc<U>&) { return false; }
int main()
{
    // std::queueにはcapacity()関数がありません(std::vectorのように)
    // このため、shrink_to_fitの動作を示すためにカスタムアロケータを使用します
    std::cout << "Default-construct deque:\n";
    std::deque<int, NAlloc<int>> deq;
    std::cout << "\nAdd 300 elements:\n";
    for (int i = 1000; i < 1300; ++i)
        deq.push_back(i);
    std::cout << "\nPop 100 elements:\n";
    for (int i = 0; i < 100; ++i)
        deq.pop_front();
    std::cout << "\nRun shrink_to_fit:\n";
    deq.shrink_to_fit();
    std::cout << "\nDestroy deque as it goes out of scope:\n";
}

出力例:

Default-construct deque:
allocating 64 bytes
allocating 512 bytes
Add 300 elements:
allocating 512 bytes
allocating 512 bytes
Pop 100 elements:
Run shrink_to_fit:
allocating 64 bytes
allocating 512 bytes
allocating 512 bytes
deallocating 512 bytes
deallocating 512 bytes
deallocating 512 bytes
deallocating 64 bytes
Destroy deque as it goes out of scope:
deallocating 512 bytes
deallocating 512 bytes
deallocating 64 bytes

欠陥報告

以下の動作変更の欠陥報告書は、以前に公開されたC++規格に対して遡及的に適用されました。

DR 適用対象 公開時の動作 正しい動作
LWG 850 C++98 std::deque に明示的なshrink-to-fit操作が欠如 提供
LWG 2033 C++98
C++11
1. 計算量要件が欠如(C++98)
2. T MoveInsertable であることが要求されていなかった(C++11)
1. 追加
2. 要求
LWG 2223 C++98
C++11
1. 参照、ポインタ、イテレータが無効化されない(C++98)
2. 例外安全性保証が存在しなかった(C++11)
1. 無効化される可能性あり
2. 追加

関連項目

要素数を返す
(公開メンバ関数)