When using algorithms like std::remove()
or std::remove_if()
from the C++ Standard Library, the elements to be removed are shifted to the end of the container, but the container's size remains unchanged.
To fully remove these elements and adjust the container size, you can use the remove-erase idiom.
Here's how you can do it:
std::remove()
or std::remove_if()
algorithm to shift the unwanted elements to the end.erase()
method to remove the surplus elements.For example, let's remove all occurrences of the number 3 from a std::vector
:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> Source{1, 2, 3, 4, 5, 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,
The std::remove()
function reorders the container so that all elements not equal to 3 are moved to the front, and the erase()
method removes the unwanted surplus elements from the end.
This method is efficient and commonly used in C++ to manage container sizes properly after removal operations.
Remember, the same concept can be applied to other containers like std::deque
or std::list
by using their respective erase()
 methods.
Answers to questions are automatically generated and may not have been reviewed.
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()
.