名前空間
変種
操作

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

From cppreference.com
< cpp‎ | コンテナ‎ | deque
 
 
 
 
void shrink_to_fit();

未使用のキャパシティの削除を要求します。

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

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

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

(C++11以降)

目次

[編集] 計算量

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

例外

CopyInsertableでないTのムーブコンストラクタによるもの以外で例外がスローされた場合、影響はありません。

(C++11以降)

[編集] 備考

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

[編集]

#include <cstddef>
#include <deque>
#include <iostream>
#include <new>
 
// Minimal C++11 allocator with debug output.
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 has no capacity() function (like std::vector).
    // Because of this, we use a custom allocator to show the
    // working of 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. TMoveInsertableである必要がなかった (C++11)
1. 追加された
2. 必須となった
LWG 2223 C++98
C++11
1. 参照、ポインタ、およびイテレータは無効化されなかった (C++98)
2. 例外安全保証がなかった (C++11)
1. 無効化される可能性がある
2. 追加された

[編集] 関連項目

要素数を返す
(public メンバ関数) [編集]
English 日本語 中文(简体) 中文(繁體)