在线文档教程
C++
容器 | Containers

std::vector::reserve

STD::载体::储备金

void reserve( size_type new_cap

将容器容量提高到大于或等于%27s的值new_cap.如果new_cap大于当前capacity(),则分配新存储空间,否则该方法将不执行任何操作。

如果new_cap大于capacity(),所有迭代器,包括过去的结束迭代器,以及所有对元素的引用都无效.。否则,没有迭代器或引用无效。

参数

new_cap-new capacity of the container

类型要求

-T必须符合MoveInserable的要求。

返回值

%280%29

例外

  • std::length_error如果new_cap > max_size()...

  • 引发的任何异常Allocator::allocate()%28典型std::bad_alloc%29

复杂性

最多是线性的size()集装箱的。

注记

reserve()不能用于减少集装箱的容量,为此目的shrink_to_fit()提供。

正确使用reserve()可以防止不必要的重新分配,但不适当地使用reserve()%28例如,在每个push_back()调用%#number0#实际上增加了重分配的数量%28,因为它导致容量线性增长,而不是指数增长的%29,从而导致计算复杂度的增加和性能的下降。

二次

#include <cstddef> #include <new> #include <vector> #include <iostream> // 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() { 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

二次

另见

capacityreturns the number of elements that can be held in currently allocated storage (public member function)
max_sizereturns the maximum possible number of elements (public member function)
resizechanges the number of elements stored (public member function)
shrink_to_fit (C++11)reduces memory usage by freeing unused memory (public member function)

© cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

http://en.cppreference.com/w/cpp/容器/载体/备用