Remove from beginning of a vector in C++
This post will discuss how to remove from the beginning of a vector in C++.
1. Using vector::erase
The recommended solution to remove an element from a vector is using the vector::erase function. It takes an iterator to the element to be deleted. To remove an element from the beginning of a vector, pass an iterator to the first element in the vector. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <vector> int main() { std::vector<int> vec = {1, 2, 3, 4}; vec.erase(vec.begin()); for (int &i: vec) { std::cout << i << ' '; } return 0; } |
Output:
2 3 4
2. Using std::deque
A std::deque is preferred to add or remove elements from either end of a container. It implements a Double-ended queue that expands or shrinks on both ends. To remove an element from the beginning of the vector, use the pop_front member function of std::deque.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <deque> int main() { std::deque<int> q = {1, 2, 3, 4}; q.pop_front(); for (int &i: q) { std::cout << i << ' '; } return 0; } |
Output:
2 3 4
That’s all about removing from the beginning of a vector in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)