所以我一直在尋找實際上動態數組的工作原理。我發現的是兩個不同的概念。爲什麼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倍。 –