Remove and Erase in std::deque
How do I remove elements from a std::deque using the remove-erase idiom?
The std::deque (double-ended queue) container in C++ allows efficient insertions and deletions at both ends.
To remove elements from a std::deque using the remove-erase idiom, you follow a similar approach as with std::vector.
Here's an example to remove all occurrences of the number 3 from a std::deque:
#include <algorithm>
#include <deque>
#include <iostream>
int main() {
std::deque<int> Source{1, 2, 3, 4, 5, 3, 6};
// Step 1: Apply std::remove
auto NewEnd = std::remove(
Source.begin(), Source.end(), 3);
// Step 2: Erase surplus elements
Source.erase(NewEnd, Source.end());
// Display the result
std::cout << "Objects in Source: ";
for (auto Num : Source) {
std::cout << Num << ", ";
}
}Objects in Source: 1, 2, 4, 5, 6,In this example:
std::remove()shifts the elements to be removed (the number 3) to the end of thestd::deque.- The
erase()method then removes these surplus elements, resizing the container accordingly.
Removing Elements Based on a Condition
You can also remove elements based on a condition using std::remove_if(). Here's how you can remove all even numbers from a std::deque:
#include <algorithm>
#include <deque>
#include <iostream>
int main() {
std::deque<int> Source{1, 2, 3, 4, 5, 6};
// Step 1: Apply std::remove_if
auto NewEnd = std::remove_if(
Source.begin(), Source.end(),
[](int x) { return x % 2 == 0; }
);
// Step 2: Erase surplus elements
Source.erase(NewEnd, Source.end());
// Display the result
std::cout << "Objects in Source: ";
for (auto Num : Source) {
std::cout << Num << ", ";
}
}Objects in Source: 1, 3, 5,In this example:
- We use
std::remove_if()with a lambda function as the predicate to remove even numbers. std::remove_if()moves the elements to be removed to the end of thestd::deque.- The
erase()method is then used to remove the surplus elements and adjust the container's size.
Using the remove-erase idiom with std::deque ensures efficient removal of elements and proper resizing of the container. This approach can be adapted to various conditions and element types, providing a flexible solution for container management.
Removal Algorithms
An overview of the key C++ standard library algorithms for removing objects from containers. We cover remove(), remove_if(), remove_copy(), and remove_copy_if().