std::deque<T,Allocator>::shrink_to_fit
來自 cppreference.com
void shrink_to_fit(); |
||
請求移除未使用的容量。
這是一個非強制性請求,用於減少記憶體使用而不改變序列的大小。請求是否被滿足取決於實現。
所有迭代器(包括end()
迭代器)和所有對元素的引用都將失效。
如果 `T` 不可移動插入(MoveInsertable)到 std::deque<T, Allocator> 中,則行為未定義。 |
(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++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
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. 已新增 |
[編輯] 另請參閱
返回元素數量 (公共成員函式) |