Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::remove_if — logical removal by predicate

std::remove_if moves retained elements to the front of a range and returns its new logical end. It does not change the container's size; for std::vector, erase completes the removal.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <algorithm>

template<class ForwardIterator, class Predicate>
constexpr ForwardIterator remove_if(ForwardIterator first, ForwardIterator last, Predicate pred);

// Usage:
auto new_end = std::remove_if(first, last, pred);

std::remove_if, declared in <algorithm>, processes [first, last). The predicate pred identifies elements to remove: a result interpreted as true means discard. Retained elements move to the front without changing their relative order. The returned iterator new_end marks the end of the retained values.

The algorithm does not shrink the container. Elements in [new_end, last) still exist but have valid, unspecified states: do not treat this tail as a collection of the discarded values. For std::vector, calling values.erase(new_end, values.end()) removes that tail. This is the erase-remove idiom; use the range overload of erase.

The shown overload without an execution policy requires mutable iterators of at least the forward category and elements meeting move-assignment requirements. The predicate must not modify the element being tested. For N elements, the algorithm makes exactly N predicate calls and has linear complexity.

If nothing is discarded, the result is last; if everything is discarded or the range is empty, the result is first. The example shows that the size is still 6 before erase, and afterward 1 3 5 remain. The source is an evolving standard draft; this description and example are limited to functionality available in C++23.

Examples

#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> values{1, 2, 3, 4, 5, 6};
    auto new_end = std::remove_if(values.begin(), values.end(),
                                  [](int x) { return x % 2 == 0; });
    std::cout << "size before erase: " << values.size() << '\n';
    values.erase(new_end, values.end());
    std::cout << "kept:";
    for (int x : values) {
        std::cout << ' ' << x;
    }
    std::cout << '\n';
}

Result

size before erase: 6
kept: 1 3 5

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources