sec*_*nes 4 c++ java arrays cross-language stdvector
所以我一直在寻找动态数组的实际工作方式.我发现的是两个不同的概念.
在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;
}
Run Code Online (Sandbox Code Playgroud)
用于扩展矢量大小
/*
* 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;
}
Run Code Online (Sandbox Code Playgroud)
在Java中
在java中,动态数组是使用arrayList实现的,它们将容量设置为10(基于JVM),一旦容量满,它们就会增加容量.将容量设置为10的原因是您不必为每次新插入频繁初始化内存.一旦容量完全增加容量大小.
好奇心
为什么在vector.h中实现将默认值设置为0?将容量设置为某个较小的值(比方说10)而不是将其设置为0可以节省每次用户插入一些元素时初始化内存的开销.
由于它是一个动态阵列,因此设置较小的矢量容量不会造成任何伤害,因为动态阵列的大小通常超过10.
编辑:我的问题是为什么默认0?默认情况下,它可以是任何小值,因为无论如何,矢量将扩展到某个特定大小,这就是首先使用向量的目的.
默认情况下,容量为零具有以下优点:默认构造a std::vector根本不进行任何动态内存分配(您不需要为不需要的内容付费).如果您知道需要~10个元素,则可以通过调用显式设置容量std::vector::reserve:
std::vector<int> vec;
vec.reserve(10);
Run Code Online (Sandbox Code Playgroud)
我只能推测,为什么Java做的事情有所不同,但afaik,动态内存分配在Java中比在c ++中更便宜,而且这两种语言在性能/低级别控制与简单性方面也遵循不同的理念.