C++ vector 关于容器扩容思考 对比Python

8 篇文章 0 订阅

前言

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

  • 将很多数组操作的细节封装起来,如数组插入、删除数据时需要搬移其他数据等
  • 支持动态扩容,每次存储空间不够的时候,它都会将空间自动扩容为 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倍扩容时,空间可重用。

在这里插入图片描述
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;
}

在这里插入图片描述

2) gcc

代码同上
在这里插入图片描述

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)


在这里插入图片描述

发现前面是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;
}


参考

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值