std::erase, std::erase_if(std::basic_string) - cppreference.com

From cppreference.com

Defined in header

<string>

template<classCharT,classTraits,classAlloc,classU>constexprstd::basic_string<CharT,Traits,Alloc>::size_typeerase(std::basic_string<CharT,Traits,Alloc>&c,constU&value); (1)(since C++20)
(until C++26)template<classCharT,classTraits,classAlloc,classU=CharT>constexprstd::basic_string<CharT,Traits,Alloc>::size_typeerase(std::basic_string<CharT,Traits,Alloc>&c,constU&value);(since C++26)template<classCharT,classTraits,classAlloc,classPred>constexprstd::basic_string<CharT,Traits,Alloc>::size_typeerase_if(std::basic_string<CharT,Traits,Alloc>&c,Predpred); (2) (since C++20)1) Erases all elements that compare equal to value from the container. Equivalent to

autoit=std::remove(c.begin(),c.end(),value);autor=c.end()-it;c.erase(it,c.end());returnr;2) Erases all elements that satisfy the predicate pred from the container. Equivalent to

autoit=std::remove_if(c.begin(),c.end(),pred);autor=c.end()-it;c.erase(it,c.end());returnr;Parameters

c - container from which to erase value - value to be removed pred - unary predicate which returns ​true if the element should be erased. The expression pred(v) must be convertible to bool for every argument v of type (possibly const) CharT, regardless of

value category

, and must not modify v. Thus, a parameter type of CharT&is not allowed, nor is CharT unless for CharT a move is equivalent to a copy(since C++11). ​

Return value

The number of erased elements.

Complexity

Linear.

Notes

Feature-test

macroValueStdFeature

__cpp_lib_algorithm_default_value_type

202403

(C++26)

List-initialization

for algorithm (

1

)Example

Run this code

#include<iomanip>#include<iostream>#include<string>intmain(){std::stringword{"startling"};std::cout<<"Initially, word = "<<std::quoted(word)<<'\n';std::erase(word,'l');std::cout<<"After erase 'l': "<<std::quoted(word)<<'\n';autoerased=std::erase_if(word,[](charx){returnx=='a'orx=='r'orx=='t';});std::cout<<"After erase all 'a', 'r', and 't': "<<std::quoted(word)<<'\n';std::cout<<"Erased symbols count: "<<erased<<'\n';#if __cpp_lib_algorithm_default_value_typestd::erase(word,{'g'});std::cout<<"After erase {'g'}: "<<std::quoted(word)<<'\n';#endif}Possible output:

Initially, word = "startling" After erase 'l', word = "starting" After erase all 'a', 'r', and 't': "sing" Erased symbols count: 4 After erase {'g'}: "sin" See also