【发布时间】:2013-06-08 17:04:25
【问题描述】:
我在所有关于动态数组的书籍中都进行了研究。我在 C++ 的 STL 中使用过它们。 但我仍然不清楚什么是动态数组。动态数组的操作是如何实现的。
【问题讨论】:
标签: c++ arrays data-structures stl operations
我在所有关于动态数组的书籍中都进行了研究。我在 C++ 的 STL 中使用过它们。 但我仍然不清楚什么是动态数组。动态数组的操作是如何实现的。
【问题讨论】:
标签: c++ arrays data-structures stl operations
在 C++ 中有(嗯,很快就会有!)4 种数组:C 风格的静态数组、C++11 static arrays、C++ dynamic vectors 和 C++14 dynamic arrays。
C 样式和 C++11 静态数组采用编译时常量大小参数,并且在初始化后无法放大/缩小。 C++ 动态向量在初始化时可以采用任何运行时数量的元素,之后可以放大/缩小。随着即将到来的 C++14 标准,std::dynarray 也将填补现有容器之间的一个小空白:在初始化期间它将占用运行时数量的元素,但之后不能放大/缩小。
以下是一些基本用例:
static const int N = 4; // compile-time constant int
int M = 4; // run-time int
int c[N] = { 0, 1, 2, 3 }; // C-style static array: compile-time constant size
std::array<int, N> a = { 0, 1, 2, 3 }; // C++11 static array: compile-time constant size
int rc[M] = { 0, 1, 2, 3 }; // ERROR: M is not a compile-time constant expression
std::array<int, M> ra = { 0, 1, 2, 3 }; // ERROR: M is not a compile-time constant expression
std::vector<int> v { std::begin(a), std::end(a) }; // C++ dynamic vector: runtime size, but can be enlarged afterwards
v.push_back(4); // v enlarged to { 0, 1, 2, 3, 4 } now
v.pop_back(); // v shrunk back to { 0, 1, 2, 3 }
std::dynarray<int> d { std::begin(v), std::end(v) }; // C++14 dynamic array: runtime size, but cannot be enlarged afterwards
静态数组(C 风格数组,std::array)在堆栈上进行静态内存分配。动态数组(std::vector<T> 和 std::dynarray<T>)可以采用 Allocator 模板参数。对于std::vector,此分配器默认为std::allocator<T>,它使用new 在后台进行动态低级内存管理。对于std::dynarray,内存是从一个未指定的源分配的,它可能会或可能不会调用全局operator new。
通过提供用户定义的分配器,std::vector 和 std::dynarray 都可以使用基于堆栈的内存分配,例如使用@HowardHinnant 的stack allocator。
【讨论】: