如何对动态数组执行操作?

时间:2013-06-08 17:04:26

标签: c++ arrays data-structures stl operations

我在有关Dymanic阵列的书籍中到处研究过。我在C ++的STL中使用过它们。 但我还不清楚什么是动态阵列。如何实现动态数组的操作。

1 个答案:

答案 0 :(得分:1)

在C ++中有(好吧,很快就会!)4种数组:C风格的静态数组,C ++ 11 static arrays,C ++ dynamic vectors和C ++ 14 {{ 3}}。

C-style和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>)可以采用dynamic arrays模板参数。对于std::vector,此分配器默认为Allocator,后者使用std::allocator<T>在幕后进行动态低级内存管理。对于std::dynarray,内存是从未指定的源分配的,该源可能会也可能不会调用全局operator new

通过提供用户定义的分配器,std::vectorstd::dynarray都可以用于基于堆栈的内存分配,例如:使用@HowardHinnant&#39; s new

相关问题