std::erase, std::erase_if (std::forward_list)
提供: cppreference.com
| ヘッダ <forward_list> で定義
|
||
template< class T, class Alloc, class U > typename std::forward_list<T,Alloc>::size_type erase(std::forward_list<T,Alloc>& c, const U& value); |
(1) | (C++20以上) |
template< class T, class Alloc, class Pred > typename std::forward_list<T,Alloc>::size_type erase_if(std::forward_list<T,Alloc>& c, Pred pred); |
(2) | (C++20以上) |
1)
value と等しいすべての要素をコンテナから削除します。 return c.remove_if([&](auto& elem) { return elem == value; }); と同等です。2) 述語
pred を満たすすべての要素をコンテナから削除します。 return c.remove_if(pred); と同等です。引数
| c | - | 削除元のコンテナ |
| value | - | 削除する値 |
| pred | - | 要素を削除するべき場合に true を返す単項述語。 式 |
戻り値
削除した要素の数。
計算量
線形。
例
Run this code
#include <iostream>
#include <numeric>
#include <forward_list>
void print_container(const std::forward_list<char>& c)
{
for (auto x : c) {
std::cout << x << ' ';
}
std::cout << '\n';
}
int main()
{
std::forward_list<char> cnt(10);
std::iota(cnt.begin(), cnt.end(), '0');
std::cout << "Init:\n";
print_container(cnt);
std::erase(cnt, '3');
std::cout << "Erase \'3\':\n";
print_container(cnt);
auto erased = std::erase_if(cnt, [](char x) { return (x - '0') % 2 == 0; });
std::cout << "Erase all even numbers:\n";
print_container(cnt);
std::cout << "In all " << erased << " even numbers were erased.\n";
}
出力:
Init:
0 1 2 3 4 5 6 7 8 9
Erase '3':
0 1 2 4 5 6 7 8 9
Erase all even numbers:
1 3 7 9
In all 5 even numbers were erased.
ノート
std::forward_list::remove と異なり、 erase は異なる型を受理し、 == 演算子を呼ぶ前にコンテナの値型への変換を強制しません。
関連項目
| 一定の基準を満たす要素を削除します (関数テンプレート) | |
| 特定の基準を満たす要素を削除します (パブリックメンバ関数) |