std::erase, std::erase_if (std::basic_string)
From cppreference.com
< cpp | string | basic string
Defined in header <string>
|
||
template< class CharT, class Traits, class Alloc, class U > constexpr typename std::basic_string<CharT, Traits, Alloc>::size_type |
(1) | (since C++20) |
template< class CharT, class Traits, class Alloc, class Pred > constexpr typename std::basic_string<CharT, Traits, Alloc>::size_type |
(2) | (since C++20) |
1) Erases all elements that compare equal to value from the container. Equivalent to
auto it = std::remove(c.begin(), c.end(), value); auto r = std::distance(it, c.end()); c.erase(it, c.end()); return r;
2) Erases all elements that satisfy the predicate pred from the container. Equivalent to
auto it = std::remove_if(c.begin(), c.end(), pred); auto r = std::distance(it, c.end()); c.erase(it, c.end()); return r;
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 |
Return value
The number of erased elements.
Complexity
Linear.
Example
Run this code
#include <iomanip> #include <iostream> #include <string> int main() { std::string word{"startling"}; std::cout << "Initially, word = " << std::quoted(word) << '\n'; std::erase(word, 'l'); std::cout << "After erase 'l': " << std::quoted(word) << '\n'; auto erased = std::erase_if(word, [](char x) { return x == 'a' or x == 'r' or x == 't'; }); std::cout << "After erase all 'a', 'r', and 't': " << std::quoted(word) << '\n'; std::cout << "Erased symbols count: " << erased << '\n'; }
Output:
Initially, word = "startling" After erase 'l', word = "starting" After erase all 'a', 'r', and 't': "sing" Erased symbols count: 4
See also
removes elements satisfying specific criteria (function template) |