![]() |
VOOZH | about |
The std::erase_if() is a utility introduced in C++20 that is used to remove elements from containers based on a specified condition. This function erases all elements that satisfy a given predicate from standard containers like std::vector, std::deque, std::list, std::forward_list, std::string, and associative containers.
In this article, we will learn about the erase_if() function, its syntax, usage scenarios, and practical examples to demonstrate how it can be used effectively in C++ programming.
erase_if(container, predicate);The std::erase_if() function returns the number of elements removed from the container.
The erase_if() function is supported for the following standard containers:
The below examples demonstrates how we can use the erase_if() function to remove elements from a container based on a condition.
Output
Number of elements removed: 3
Remaining elements: 1 3 5 7
Time Complexity: O(n), where n is the number of elements in the vector.
Auxiliary Space: O(1)
Output
Number of elements removed: 2
Remaining elements: {2, 200} {3, 150} {5, 250}
Time Complexity: The time complexity of the std::erase_if() function depends on the container type:
Auxiliary Space: The auxiliary space required by std::erase_if() is O(1) as it operates in-place within the container.