Skip to main content

std::remove_if() algorithm

// (1)
template< class ForwardIt, class UnaryPredicate >
constexpr ForwardIt remove_if( ForwardIt first, ForwardIt last, UnaryPredicate p );

// (2)
template< class ExecutionPolicy, class ForwardIt, class UnaryPredicate >
ForwardIt remove_if( ExecutionPolicy&& policy,
ForwardIt first, ForwardIt last, UnaryPredicate p );

Removes all elements satisfying specific criteria from the range [first; last) and returns a past-the-end iterator for the new end of the range.

  • (1) Removes all elements for which predicate p returns true.

  • (2) Same as (1), but executed according to policy.

    Overload Resolution

    These overloads participate in overload resolution only if std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>  (until C++20) std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>  (since C++20) is true.

If the type of *first is not MoveAssignable, the behaviour is undefined.

Removing is done by shifting (by means of move assignment (since C++11)copy assignment (until C++11)) the elements in the range in such a way that the elements that are not to be removed appear in the beginning of the range.

important

Relative order of the elements that remain is preserved and the physical size of the container is unchanged.

warning

Iterators pointing to an element between the new logical end and the physical end of the range are still dereferenceable, but the elements themselves have unspecified values (as per MoveAssignable post-condition). (since C++11)

Parameters

first
last

The range of elements to process.

policy

The execution policy to use. See execution policy for details.

p

Unary predicate which returns true if the element should be removed.

The expression p(v) must be convertible to bool for every argument v of type (possibly const) VT, where VT is the value type of InputIt, regardless of value category, and must not modify v. Thus, a parameter type of VT& is not allowed , nor is VT unless for VT a move is equivalent to a copy. (since C++11).

Type requirements

ForwardItLegacyForwardIterator
UnaryPredicatePredicate

Return value

Past-the-end iterator for the new range of values (if this is not end, then it points to an unspecified value, and so do iterators to any values between this iterator and end).

Complexity

Given N as std::distance(first, last):

At most N applications of predicate p.

Exceptions

The overloads with a template parameter named ExecutionPolicy report errors as follows:

  • If execution of a function invoked as part of the algorithm throws an exception and ExecutionPolicy is one of the standard policies, std::terminate is called. For any other ExecutionPolicy, the behavior is implementation-defined.
  • If the algorithm fails to allocate memory, std::bad_alloc is thrown.

Possible implementation

remove_if (1)
template<class ForwardIt, class UnaryPredicate>
ForwardIt remove_if(ForwardIt first, ForwardIt last, UnaryPredicate p)
{
first = std::find_if(first, last, p);
if (first != last)
for (ForwardIt i = first; ++i != last;)
if (!p(*i))
*first++ = std::move(*i);
return first;
}

Notes

A call to remove_if is typically followed by a call to a container's erase member function, which erases the unspecified values and reduces the physical size of the container to match its new logical size. These two invocations together constitute a so-called Erase–remove_if idiom, which can be achieved by the free function std::erase that has overloads for all standard sequence containers, or std::erase_if that has overloads for all standard containers (since C++20)

The similarly-named container member functions list::remove_if, list::remove_if_if, forward_list::remove_if, and forward_list::remove_if_if erase the remove_ifd elements.

These algorithms cannot be used with associative containers such as std::set and std::map because their iterator types do not dereference to MoveAssignable types (the keys in these containers are not modifiable).

Examples

The following code remove_ifs all spaces from a string by shifting all non-space characters to the left and then erasing the extra. This is an example of Erase-remove idiom.

Main.cpp
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
#include <string_view>

int main()
{
std::string str1 {"Text with some spaces"};

auto noSpaceEnd = std::remove_if(str1.begin(), str1.end(), ' ');

// The spaces are remove_ifd from the string only logically.
// Note, we use view, the original string is still not shrunk:
std::cout << std::string_view(str1.begin(), noSpaceEnd)
<< " size: " << str1.size() << '\n';

str1.erase(noSpaceEnd, str1.end());

// The spaces are remove_ifd from the string physically.
std::cout << str1 << " size: " << str1.size() << '\n';

std::string str2 = "Text\n with\tsome \t whitespaces\n\n";
str2.erase(std::remove_if_if(str2.begin(),
str2.end(),
[](unsigned char x) { return std::isspace(x); }),
str2.end());
std::cout << str2 << '\n';
}
Output
Textwithsomespaces size: 23
Textwithsomespaces size: 18
Textwithsomewhitespaces
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.

std::remove_if() algorithm

// (1)
template< class ForwardIt, class UnaryPredicate >
constexpr ForwardIt remove_if( ForwardIt first, ForwardIt last, UnaryPredicate p );

// (2)
template< class ExecutionPolicy, class ForwardIt, class UnaryPredicate >
ForwardIt remove_if( ExecutionPolicy&& policy,
ForwardIt first, ForwardIt last, UnaryPredicate p );

Removes all elements satisfying specific criteria from the range [first; last) and returns a past-the-end iterator for the new end of the range.

  • (1) Removes all elements for which predicate p returns true.

  • (2) Same as (1), but executed according to policy.

    Overload Resolution

    These overloads participate in overload resolution only if std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>  (until C++20) std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>  (since C++20) is true.

If the type of *first is not MoveAssignable, the behaviour is undefined.

Removing is done by shifting (by means of move assignment (since C++11)copy assignment (until C++11)) the elements in the range in such a way that the elements that are not to be removed appear in the beginning of the range.

important

Relative order of the elements that remain is preserved and the physical size of the container is unchanged.

warning

Iterators pointing to an element between the new logical end and the physical end of the range are still dereferenceable, but the elements themselves have unspecified values (as per MoveAssignable post-condition). (since C++11)

Parameters

first
last

The range of elements to process.

policy

The execution policy to use. See execution policy for details.

p

Unary predicate which returns true if the element should be removed.

The expression p(v) must be convertible to bool for every argument v of type (possibly const) VT, where VT is the value type of InputIt, regardless of value category, and must not modify v. Thus, a parameter type of VT& is not allowed , nor is VT unless for VT a move is equivalent to a copy. (since C++11).

Type requirements

ForwardItLegacyForwardIterator
UnaryPredicatePredicate

Return value

Past-the-end iterator for the new range of values (if this is not end, then it points to an unspecified value, and so do iterators to any values between this iterator and end).

Complexity

Given N as std::distance(first, last):

At most N applications of predicate p.

Exceptions

The overloads with a template parameter named ExecutionPolicy report errors as follows:

  • If execution of a function invoked as part of the algorithm throws an exception and ExecutionPolicy is one of the standard policies, std::terminate is called. For any other ExecutionPolicy, the behavior is implementation-defined.
  • If the algorithm fails to allocate memory, std::bad_alloc is thrown.

Possible implementation

remove_if (1)
template<class ForwardIt, class UnaryPredicate>
ForwardIt remove_if(ForwardIt first, ForwardIt last, UnaryPredicate p)
{
first = std::find_if(first, last, p);
if (first != last)
for (ForwardIt i = first; ++i != last;)
if (!p(*i))
*first++ = std::move(*i);
return first;
}

Notes

A call to remove_if is typically followed by a call to a container's erase member function, which erases the unspecified values and reduces the physical size of the container to match its new logical size. These two invocations together constitute a so-called Erase–remove_if idiom, which can be achieved by the free function std::erase that has overloads for all standard sequence containers, or std::erase_if that has overloads for all standard containers (since C++20)

The similarly-named container member functions list::remove_if, list::remove_if_if, forward_list::remove_if, and forward_list::remove_if_if erase the remove_ifd elements.

These algorithms cannot be used with associative containers such as std::set and std::map because their iterator types do not dereference to MoveAssignable types (the keys in these containers are not modifiable).

Examples

The following code remove_ifs all spaces from a string by shifting all non-space characters to the left and then erasing the extra. This is an example of Erase-remove idiom.

Main.cpp
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
#include <string_view>

int main()
{
std::string str1 {"Text with some spaces"};

auto noSpaceEnd = std::remove_if(str1.begin(), str1.end(), ' ');

// The spaces are remove_ifd from the string only logically.
// Note, we use view, the original string is still not shrunk:
std::cout << std::string_view(str1.begin(), noSpaceEnd)
<< " size: " << str1.size() << '\n';

str1.erase(noSpaceEnd, str1.end());

// The spaces are remove_ifd from the string physically.
std::cout << str1 << " size: " << str1.size() << '\n';

std::string str2 = "Text\n with\tsome \t whitespaces\n\n";
str2.erase(std::remove_if_if(str2.begin(),
str2.end(),
[](unsigned char x) { return std::isspace(x); }),
str2.end());
std::cout << str2 << '\n';
}
Output
Textwithsomespaces size: 23
Textwithsomespaces size: 18
Textwithsomewhitespaces
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.