Last Updated : 23 Jul, 2025
std::remove_if() is a built-in algorithm of the C++ STL that is used to remove elements from a specified range of elements that satisfies the given condition. The condition can be defined as a function, lambda expression or a function object. It is defined inside the <algorithm> header file.
In this article, we will learn how to remove elements from a container based on a condition using std::remove_if in C++.
Example:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 2, 3, 4, 5, 6};
// Remove all even numbers from vector v
auto ne = remove_if(v.begin(), v.end(),
[](int x) {
return x % 2 == 0;
});
v.erase(ne, v.end());
for (auto i : v)
cout << i << " ";
return 0;
}
Just like std::remove() algorithm, std::remove_if() doesn't actually delete the elements from the container. It only moves the elements that satisfies the given condition to the end of the container and returns an iterator to the new end of the range that contains the elements that should be kept. We need to use the erase function of corresponding container (if any) with std::remove_if() to actually delete the elements.
std::remove_if SyntaxParametersstd::remove_if(first, last, p);
std::remove_if() can be used with containers that provide forward iterators or better, such as:
The std::remove_if() function can be used to remove elements based on a condition from various containers or arrays, as demonstrated by the examples below:
Example 1: Removing Elements from an Array Using Lambda Expression C++
// C++ program to remove elements from an array
// using std::remove_if
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
int s = sizeof(arr) / sizeof(arr[0]);
// Remove all odd numbers using std::remove_if
int* ne = remove_if(arr, arr + s, [](int x) {
return x % 2 != 0;
});
// Calculate the new size after removal
int ns = ne - arr;
for (int i = 0; i < ns; i++)
cout << arr[i] << " ";
return 0;
}
Example 2: Removing Elements from Deque Using Traditional Function C++
// C++ Program to illustrate use of std::remove_if
// wihthout erase function
#include <bits/stdc++.h>
using namespace std;
// Function that returns true for integer
// greater than 20
bool f(int a) {
return a > 20;
}
int main() {
deque<int> d = {10, 15, 20, 25, 30, 35};
// Remove elements greater than 20 from
// the deque
auto ne = remove_if(d.begin(), d.end(), f);
// Actually removing the element
d.erase(ne, d.end());
for (auto i: d)
cout << i << " ";
return 0;
}
Initial Size: 6 Size After Removal: 6
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4