Consistent Container Erasure

Understand the details of 'erase' and 'erase_if' in C++20.

Before C++20, removing elements from a container was too complicated. Let me show you why.

The erase-remove idiom

Removing an element from a container seems to be quite easy. In the case of a std::vector you can use the function std::remove_if.

Press + to interact
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::cout << '\n';
std::vector myVec{-2, 3, -5, 10, 3, 0, -5 };
for (auto ele: myVec) std::cout << ele << " ";
std::cout << "\n\n";
std::remove_if(myVec.begin(), myVec.end(), [](int ele){ return ele < 0; });
for (auto ele: myVec) std::cout << ele << " ";
std::cout << "\n\n";
}

The program above removes all elements from the std::vector that are less than zero. Easy, right? Maybe not; now, you fall into the trap that is well-known to many seasoned C++ programmers.

std::remove_if (line 13) does not remove anything. The std::vector still has the same number of elements. Both algorithms return the new logical end of the modified container.

To modify a container, you have to apply ...

Get hands-on with 1400+ tech skills courses.