C++ vector 关于容器扩容思考

在读到文章《数据结构与算法之美》关于数组和容器一节时 (笔记在此),提到 容器的优点

  • 将很多数组操作的细节封装起来,如数组插入、删除数据时需要搬移其他数据等
  • 支持动态扩容,每次存储空间不够的时候,它都会将空间自动扩容为 1.5 倍大小


为什么是1.5倍呢,这个数据是固定的吗?

于是在网上查找了资料,也对此进行了测试。

1. 网上有1.5倍和2倍两者方法,不同编译器结果不一样

  • gcc,python list是2倍 (后面有验证,python不是一直2倍)
  • VS是1.5倍

两者的区别是,2倍扩容时间复杂度更优,可以保证时间复杂度 O ( n ) O(n) O(n) ,而1.5倍扩容时,空间可重用。

C++ vector 关于容器扩容思考_第1张图片
from: c++STL vector扩容过程


2. 代码测试

1. VS2017
int main()
{
	vector<int> a;
	for (int i = 0; i < 20; i++) {
		a.push_back(i);
		cout << "size : " << i + 1 << "\t" 
		cout<< "capacity : " << a.capacity() << endl;
	}
	system("pause");
	return 0;
}

C++ vector 关于容器扩容思考_第2张图片

2. gcc

代码同上
C++ vector 关于容器扩容思考_第3张图片

3. python3
import sys 
l = [] 
empty_size = sys.getsizeof(l) 
print("The size of an empty list :", empty_size, "bytes") 
print("In 64 bit machine,  size of a single element is 8 ")

for i in range(0, 50):
	l.append(i)
	size = len(l)
	capacity = (sys.getsizeof(l) - empty_size)//8
	print("size: ", size, "\t", "capacity:", capacity)


C++ vector 关于容器扩容思考_第4张图片

发现前面是2倍,后面就不是了。出现成正比的“线性摊销”概念。

/* This over-allocates proportional to the list size, making room
* for additional growth.  The over-allocation is mild, but is
* enough to give linear-time amortized behavior over a long
* sequence of appends() in the presence of a poorly-performing
* system realloc().
* The growth pattern is:  0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
*/
new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6);

/* check for integer overflow */
if (new_allocated > PY_SIZE_MAX - newsize) {
    PyErr_NoMemory();
    return -1;
} else {
    new_allocated += newsize;
}


参考

  • 当面试官问我们vector扩容机制时,他想问什么?
  • c++STL vector扩容过程
  • python:Size of list in memory
  • list 里的各函数及源码配图Python中list的实现

你可能感兴趣的:(C++,Python)