我在有关动态阵列的书籍中到处学习。我在 C++ 的 STL 中使用过它们。但我仍然不清楚什么是动态数组。如何实现对动态数组的操作。
user2466482
问问题
348 次
1 回答
1
在 C++ 中有(嗯,很快就会有!)4 种数组:C 风格的静态数组、C++11静态数组、C++动态向量和 C++14动态数组。
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>
) 可以采用分配器模板参数。对于std::vector
这个 Allocator 默认为std::allocator<T>
,它在后台使用new
. 因为std::dynarray
内存是从一个未指定的源分配的,它可能会也可能不会调用全局operator new
.
通过提供用户定义的分配器,两者std::vector
和std::dynarray
都可以与基于堆栈的内存分配一起使用,例如使用@HowardHinnant 的堆栈分配器。
于 2013-06-10T08:13:26.730 回答