C++ Remove Elements from a Deque
In C++, you can remove elements from a deque using the pop_front()
and pop_back()
methods to remove the first and last elements, respectively. You can also use the erase()
method to remove elements at a specified position or range of positions.
Here's an example of how to remove elements from a deque using these methods:
#include <iostream> #include <deque> int main() { std::deque<int> d {1, 2, 3, 4, 5}; // Remove the first element d.pop_front(); // Remove the last element d.pop_back(); // Remove the element at index 1 d.erase(d.begin() + 1); // Remove the elements in the range [1, 3) d.erase(d.begin() + 1, d.begin() + 3); // Print the elements of the deque for (auto it = d.begin(); it != d.end(); ++it) { std::cout << *it << " "; } std::cout << std::endl; return 0; }
In this example, we create a deque d
with five elements, and then we use the pop_front()
, pop_back()
, and erase()
methods to remove elements at different positions in the deque. We then print the values of all the remaining elements in the deque.
The output of this program is:
3
As you can see, we have successfully removed elements from the deque using the pop_front()
, pop_back()
, and erase()
methods. Note that when using the erase()
method to remove a range of elements, the range is specified using iterators that point to the first and one-past-the-last elements to be removed.