所以我一直在寻找动态数组通常是如何工作的。我发现是两个不同的概念。
在 C++ 中
在 C++ 中,动态数组一般由向量实现。向量将容量设置为 0,增加插入新元素的计数,然后将新插入的容量大小加倍。
矢量.h
/*
* Implementation notes: Vector constructor and destructor
* -------------------------------------------------------
* The constructor allocates storage for the dynamic array and initializes
* the other fields of the object. The destructor frees the memory used
* for the array.
*/
template <typename ValueType>
Vector<ValueType>::Vector() {
count = capacity = 0;
elements = NULL;
}
用于扩展矢量大小
/*
* Implementation notes: expandCapacity
* ------------------------------------
* This function doubles the array capacity, copies the old elements into
* the new array, and then frees the old one.
*/
template <typename ValueType>
void Vector<ValueType>::expandCapacity() {
capacity = max(1, capacity * 2);
ValueType *array = new ValueType[capacity];
for (int i = 0; i < count; i++) {
array[i] = elements[i];
}
if (elements != NULL) delete[] elements;
elements = array;
}
在 Java 中
在 java 中,动态数组是使用 arrayList 实现的,它们将容量设置为 10(基于 JVM),一旦容量已满,它们就会将容量增加一些。将容量设置为 10 的原因是您不必为每次新插入频繁地初始化内存。一旦容量已满,请增加容量大小。
好奇心
为什么vector.h中的实现将默认值设置为0?将容量设置为某个较小的值(比如说 10)而不是将其设置为 0,可以节省每次用户插入某个元素时初始化内存的开销。
因为是动态数组,所以设置vector的小容量是没有坏处的,因为动态数组的大小一般都在10以上。
编辑:我的问题是为什么默认 0 ?默认情况下它可以是任何小的值,因为无论如何向量都会扩展到某个特定的大小,这就是首先使用向量的目的。