小智 18
简单.试一试:
vec.erase(vec.begin());
Run Code Online (Sandbox Code Playgroud)
小智 14
vector通常实现如下:
struct
{
T* begin; // points to the first T in the vector
T* end; // points just after the last T in the vector
int capacity; // how many Ts of memory were allocated
};
Run Code Online (Sandbox Code Playgroud)
"begin"提供双重任务作为"指向向量中第一个T的指针"和"指向我们分配的所有内存的指针".因此,通过简单地增加"开始"就不可能从向量的前面"弹出"元素 - 执行此操作并且您不再需要指向需要释放的内存的指针.那会泄漏记忆.所以"pop_front"需要将所有Ts从向量的背面复制到向量的前面,这相对较慢.所以他们决定将它排除在标准之外.
你想要的是这样的:
struct
{
T* allocated; // points to all the memory we allocated
T* begin; // points to the first T in the vector
T* end; // points just after the last T in the vector
int capacity; // how many Ts of memory were allocated
};
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您可以通过向前和向后移动"开始"来"pop_front",而不会忘记以后要释放哪个内存.为什么std :: vector不以这种方式工作?我想这是编写标准的人的品味问题.他们的目标可能是提供最简单的"动态可调整阵列",我认为他们成功了.
因为push_back并且pop_back是仅需要O(1)计算的向量的特殊操作.任何其他推或弹出O(n).
这不是"bug"或"quirk",这只是向量容器的属性.如果您需要快速pop_front考虑更改为其他容器.