std::vector<T,Allocator>::reserve_C++中文网
| void reserve( size_type new_cap ); |
||
增加 vector 的容量到大于或等于 new_cap 的值。若 new_cap 大于当前的 capacity() ,则分配新存储,否则该方法不做任何事。
reserve() 不更改 vector 的 size 。
若 new_cap 大于 capacity() ,则所有迭代器,包含尾后迭代器和所有到元素的引用都被非法化。否则,没有迭代器或引用被非法化。
参数
返回值
(无)
异常
- 若 new_cap > max_size() 则为 std::length_error 。
- 任何
Allocator::allocate()所抛的异常(典型为 std::bad_alloc )
若抛出异常,则此函数无效果(强异常保证)。
复杂度
至多与容器的 size() 成线性。
注意
不能用 reserve() 减少容器容量。为该目的提供的是 shrink_to_fit() 。
正确使用 reserve() 能避免不必要的分配,但不适当地使用 reserve() (例如在每次 push_back() 调用前调用它)可能会实际增加重分配的数量(通过导致容量线性而非指数增长)并导致计算复杂度增加,性能下降。
示例
#include <cstddef> #include <new> #include <vector> #include <iostream> // 带调试输出的最小 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(Tp) << " 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() { int sz = 100; std::cout << "using reserve: \n"; { std::vector<int, NAlloc<int>> v1; v1.reserve(sz); for(int n = 0; n < sz; ++n) v1.push_back(n); } std::cout << "not using reserve: \n"; { std::vector<int, NAlloc<int>> v1; for(int n = 0; n < sz; ++n) v1.push_back(n); } }
可能的输出:
using reserve: allocating 400 bytes deallocating 400 bytes not using reserve: allocating 4 bytes allocating 8 bytes deallocating 4 bytes allocating 16 bytes deallocating 8 bytes allocating 32 bytes deallocating 16 bytes allocating 64 bytes deallocating 32 bytes allocating 128 bytes deallocating 64 bytes allocating 256 bytes deallocating 128 bytes allocating 512 bytes deallocating 256 bytes deallocating 512 bytes