how is push_back implemented in STL vector?(push_back 是如何在 STL 向量中实现的?)
问题描述
我在一次采访中被问到这个问题.
I was asked this question in an interview.
我回答的点是这样的
1) 指向当前位置的索引;
1) an index pointing to the current position;
2) 必要时调整大小.
2) resize if neccessary.
谁能说得详细点?
推荐答案
STL vector 有一个 size(当前存储元素的数量)和一个 capacity(当前分配的存储空间).
An STL vector has a size (current number of stored elements) and a capacity (currently allocated storage space).
- 如果
size <容量,push_back只是将新元素放在最后,并将size增加 1. - 如果
size == capacity在push_back之前,一个新的更大的数组被分配(两倍的大小是常见的,但这是依赖于实现的afaik),所有复制当前数据(包括新元素),并释放旧分配的空间.如果分配失败,这可能会引发异常.
- If
size < capacity, apush_backsimply puts the new element at the end and increments thesizeby 1. - If
size == capacitybefore thepush_back, a new, larger array is allocated (twice the size is common, but this is implementation-dependent afaik), all of the current data is copied over (including the new element), and the old allocated space is freed. This may throw an exception if the allocation fails.
操作的复杂性摊销 O(1),这意味着在导致调整大小的push_back期间,它不会是一个恒定时间的操作(但总的来说,在许多操作中,它是).
The complexity of the operation is amortized O(1), which means during a push_back that causes a resize, it won't be a constant-time operation (but in general over many operations, it is).
这篇关于push_back 是如何在 STL 向量中实现的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:push_back 是如何在 STL 向量中实现的?
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
