Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::erase: removing every element equal to a value

std::erase removes every element equal to a supplied value from a supported sequence container or string and returns the removal count.

Version: C++23

Syntax

template<class T, class Allocator, class U>
constexpr typename std::vector<T, Allocator>::size_type
erase(std::vector<T, Allocator>& c, const U& value);
// Corresponding overloads exist for other supported sequence containers and basic_string.

std::erase(c, value) is a family of free overloads provided by each container header, including those for vector, deque, list, forward_list, and basic_string. It modifies c in place and returns the container’s size_type count of erased elements.

For vector, deque, and strings, the effect is equivalent to remove followed by member erase; list containers use their removal mechanism. Elements are compared with ==, the relative order of survivors is preserved, and invalidation follows the underlying container’s erase rules.

This is not one template for every range: std::array has fixed size, while associative containers erase a key through their member erase. Use std::erase_if for a condition beyond equality. Avoid passing as value a reference to an element whose relocation could change the value being compared.

Examples

#include <iostream>
#include <vector>

int main() {
    std::vector<int> values{1, 2, 1, 3, 1};
    const auto removed = std::erase(values, 1);
    std::cout << removed << ' ' << values.size();
    for (int value : values) std::cout << ' ' << value;
    std::cout << '\n';
}

Result

3 2 2 3

std::erase → 3 2 2 3

Sources