为什么C++ std :: vector中没有pop_front方法?

Ale*_*son 38 c++ vector

为什么pop_frontC++中没有方法std::vector

Lig*_*ica 57

因为std::vector没有关于在前面插入元件的特定特征,不像其他一些容器.每个容器提供的功能对该容器有意义.

您可能应该使用a std::deque,明确擅长插入正面背面.

检查此图表.

  • 这并不能真正解释为什么没有 pop_front() 方法,它只讨论插入。插入元素与弹出元素有何关系? (3认同)
  • 图表不错,但全黑很难理解 (2认同)

小智 18

简单.试一试:

vec.erase(vec.begin());
Run Code Online (Sandbox Code Playgroud)

  • 这有效,但在大向量上效率不高。 (3认同)

小智 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不以这种方式工作?我想这是编写标准的人的品味问题.他们的目标可能是提供最简单的"动态可调整阵列",我认为他们成功了.


orl*_*rlp 9

因为push_back并且pop_back是仅需要O(1)计算的向量的特殊操作.任何其他推或弹出O(n).

这不是"bug"或"quirk",这只是向量容器的属性.如果您需要快速pop_front考虑更改为其他容器.

  • 具体来说,如果你需要快速的`pop_front()`,可以考虑改为`std :: deque <>`. (3认同)
  • 为什么 **pop**_front 不能是 O(1)?您只需将指向数组开头的指针前进一个元素吗? (3认同)