Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there is no pop_front method in C++ std::vector?

Tags:

c++

vector

Why there is no pop_front method in C++ std::vector?

like image 731
Alessandro Jacopson Avatar asked Apr 06 '11 09:04

Alessandro Jacopson


People also ask

Is there Pop_front in vector C++?

Implement pop_front operation for a vector in C++The pop_front operation should remove the first element from the vector and maintain the order of the remaining elements. We know that std::vector only supports push_back and pop_back operations. Both operations run in constant time.

Is std::vector continuous?

Yes, the elements of a std::vector are guaranteed to be contiguous.

What does std::vector do?

1) std::vector is a sequence container that encapsulates dynamic size arrays. 2) std::pmr::vector is an alias template that uses a polymorphic allocator. The elements are stored contiguously, which means that elements can be accessed not only through iterators, but also using offsets to regular pointers to elements.


2 Answers

Because a std::vector has no particular feature regarding inserting elements at the front, unlike some other containers. The functionality provided by each container makes sense for that container.

You probably should be using a std::deque, which is explicitly good at inserting at the front and back.

Check this diagram out.

like image 90
Lightness Races in Orbit Avatar answered Sep 28 '22 05:09

Lightness Races in Orbit


Although inefficient on large vectors, the following is equivalent to a pop_front() for a std::vector

vec.erase(vec.begin()); 

As stated in other answers, std::vector is not designed to remove the first element and will require to move/copy all remaining elements. Depending on the specific use case, it might be convenient to consider other containers.

like image 39
SEGStriker Avatar answered Sep 28 '22 04:09

SEGStriker