Difference between revisions of "Template:cpp/container/erase2"
From cppreference.com
(Add example) |
m (generalize) |
||
Line 51: | Line 51: | ||
#include <iostream> | #include <iostream> | ||
#include <numeric> | #include <numeric> | ||
− | #include < | + | #include <{{#switch:{{{1}}}|basic_string=string|{{{1}}}}}> |
− | void | + | void print_container(const std::{{#switch:{{{1}}}|basic_string=string|{{{1}}}<char>}}& v) |
{ | { | ||
for (auto x : v) { | for (auto x : v) { | ||
Line 63: | Line 63: | ||
int main() | int main() | ||
{ | { | ||
− | std:: | + | std::{{#switch:{{{1}}}|basic_string=string|{{{1}}}<char>}} cnt(10); |
− | std::iota( | + | std::iota(cnt.begin(), cnt.end(), '0'); |
std::cout << "Init:\n"; | std::cout << "Init:\n"; | ||
− | + | print_container(v); | |
− | std::erase(v, 5); | + | std::erase(v, '5'); |
− | std::cout << "Erase 5:\n"; | + | std::cout << "Erase \'5\':\n"; |
− | + | print_container(v); | |
− | std::erase_if(v, []( | + | std::erase_if(v, [](char x) { return (x - '0') % 2 == 0; }); |
std::cout << "Erase all even numbers:\n"; | std::cout << "Erase all even numbers:\n"; | ||
− | + | print_container(v); | |
} | } | ||
| output= | | output= |
Revision as of 23:18, 3 October 2019
{{cpp/container/{{{1}}}/navbar}}
Defined in header [[cpp/header/{{{1}}}|<{{{1}}}>]]
|
||
template< ..., class U > void erase(std::{{{1}}}<...>& c, const U& value); |
(1) | (since C++20) |
template< ..., class Pred > void erase_if(std::{{{1}}}<...>& c, Pred pred); |
(2) | (since C++20) |
1) Erases all elements that compare equal to
value
from the container. 2) Erases all elements that satisfy the predicate
pred
from the container. Contents |
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 |
Complexity
Linear.
Example
Run this code
#include <iostream> #include <numeric> #include <{{{1}}}> void print_container(const std::{{{1}}}<char>& v) { for (auto x : v) { std::cout << x << ' '; } std::cout << '\n'; } int main() { std::{{{1}}}<char> cnt(10); std::iota(cnt.begin(), cnt.end(), '0'); std::cout << "Init:\n"; print_container(v); std::erase(v, '5'); std::cout << "Erase \'5\':\n"; print_container(v); std::erase_if(v, [](char x) { return (x - '0') % 2 == 0; }); std::cout << "Erase all even numbers:\n"; print_container(v); }
Output:
Init: 0 1 2 3 4 5 6 7 8 9 Erase 5: 0 1 2 3 4 6 7 8 9 Erase all even numbers: 1 3 7 9
See also
removes elements satisfying specific criteria (function template) |