std::deque shrink_to_fit() 方法
- 自 C++11 起
// Non const version only
void shrink_to_fit();
请求将未使用的容量减少到 size()
。
重要
容量是否会减少取决于实现。
失效
如果发生重新分配,所有迭代器(包括超出末端迭代器)以及对元素的所有引用都将失效。
如果没有发生重新分配,任何迭代器或引用都不会失效。
参数
(无)
类型要求
T
(容器的元素类型)必须满足MoveInsertable
的要求。
返回值
(无)
复杂度
最多与容器大小呈线性关系 - O(size())。
异常
如果抛出异常,而不是由T
的移动构造函数抛出,则此函数没有效果(强异常保证)。
示例
Main.cpp
#include <iostream>
#include <new>
#include <deque>
// 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