Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::remove — logical element removal

std::remove moves retained elements to the front of a range and returns its new logical end. It does not shrink the container; use erase to actually remove the trailing elements.

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

Syntax

#include <algorithm>

template<class ForwardIterator, class T>
constexpr ForwardIterator remove(ForwardIterator first, ForwardIterator last, const T& value);

// Usage:
auto new_end = std::remove(v.begin(), v.end(), value);
v.erase(new_end, v.end());

std::remove from <algorithm> processes [first, last): it logically eliminates elements satisfying *i == value, preserving the order of the others. It returns an iterator new_end, so the result is [first, new_end). The declaration above shows the overload without an execution policy for C++23; the linked working draft evolves and also contains later changes.

The algorithm does not change the container's size. Elements in [new_end, last) remain valid but have unspecified states; do not treat them as a collection of the removed values. For std::vector, follow it with v.erase(new_end, v.end()): this is the erase-remove idiom.

It requires at least forward iterators and elements meeting move-assignment requirements. It performs exactly as many equality comparisons as there are input elements, giving linear complexity. Do not pass a reference to an element of the modified range as value: moving elements can change that value during execution.

std::remove_if selects elements using a predicate instead of equality. The example shows the size before and after erase and prints only the retained elements.

Examples

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

int main() {
    std::vector<int> v{1, 2, 3, 2, 4};
    auto new_end = std::remove(v.begin(), v.end(), 2);

    std::cout << "size before erase: " << v.size() << '\n';
    v.erase(new_end, v.end());
    std::cout << "size after erase: " << v.size() << '\n';
    for (int x : v) {
        std::cout << x << '\n';
    }
}

Result

size before erase: 5
size after erase: 3
1
3
4

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