所以我一直在寻找实际上动态数组的工作原理。我发现的是两个不同的概念。为什么C++和Java中的动态数组具有不同的初始容量?
在C++
在C++中,动态阵列通常通过载体实现。向量将容量设置为0,增加计数以插入新元素,然后将新插入的容量大小加倍。
vector.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可以节省初始化内存的开销。
由于它是一个动态数组,矢量不会有害设置容量小,因为动态数组的大小一般超出10
编辑:我的问题是,为什么默认为0?它可以是默认的任何小值,因为无论如何矢量将扩展到某个特定的大小,这是首先使用矢量的目的。
@juanchopanza [这个问题](https://stackoverflow.com/questions/23414302/c-vector-initial-capacity)说所有着名的实现默认为0. – Barmar
@Barmar RIght,我的错误。 – juanchopanza
矢量也随着某些因素增长,它不需要是2倍。 –