namespace std::ranges {
template <permutable I,
sentinel_for<I> S,
class Proj = identity,
indirect_unary_predicate<projected<I, Proj>> Pred>
constexpr subrange<I>
remove_if(I first,
S last,
Pred pred,
Proj proj = {}); // (1) C++20
template <forward_range R,
class Proj = identity,
indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred>
requires permutable<iterator_t<R>>
constexpr borrowed_subrange_t<R>
remove_if(R&& r,
Pred pred,
Proj proj = {}); // (2) C++20
template <execution-policy Ep,
random_access_iterator I,
sized_sentinel_for<I> S,
class Proj = identity,
indirect_unary_predicate<projected<I, Proj>> Pred>
requires permutable<I>
subrange<I>
remove_if(Ep&& exec,
I first,
S last,
Pred pred,
Proj proj = {}); // (3) C++26
template <execution-policy Ep,
sized-random-access-range R,
class Proj = identity,
indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred>
requires permutable<iterator_t<R>>
borrowed_subrange_t<R>
remove_if(Ep&& exec,
R&& r,
Pred pred,
Proj proj = {}); // (4) C++26
}
概要
条件を満たす要素を除ける。
- (1): イテレータ範囲を指定する
- (2): Rangeを直接指定する
- (3): (1)の並列アルゴリズム版。実行ポリシーを指定する
- (4): (2)の並列アルゴリズム版。実行ポリシーを指定する
効果
[first,last) 内にあるイテレータ i について、invoke(pred, invoke(proj, *i)) である要素を取り除き、有効な要素を範囲の前に寄せる。
戻り値
j を有効な要素の末尾の次を指すイテレータとすると、 {j, last}
計算量
正確に last - first 回の述語の適用を行う
備考
安定。
備考
有効な要素を範囲の前方に集める処理には、ムーブを使用する。
取り除いた要素の先頭を指すイテレータをretとし、範囲[ret, last)の各要素には、有効な要素からムーブされた値が設定される。それらの値は、「有効だが未規定な値」となる。
例
基本的な使い方
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = { 2,3,1,2,1 };
auto result = std::ranges::remove_if(v, [](int x) { return x%2 != 0; });
// [v.begin(), result.begin()) の範囲に奇数を除去した結果が入っている
for (int x : std::ranges::subrange {v.begin(), result.begin()}) {
std::cout << x << ",";
}
std::cout << std::endl;
// remove を使ってもコンテナの要素数は変わらないことに注意しよう
std::cout << "size before: " << v.size() << std::endl;
// [v.begin(), result.begin()) の範囲に奇数を除去した結果が入っているので、
// [result.begin(),v.end()) を erase することでサイズも変更することができる
// (Erase-remove イディオム)
v.erase(result.begin(), v.end());
std::cout << "size after: " << v.size() << std::endl;
}
出力
2,2,
size before: 5
size after: 2
並列アルゴリズムの例 (C++26)
#include <algorithm>
#include <iostream>
#include <vector>
#include <execution>
int main() {
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// 並列に奇数を除去する
auto result = std::ranges::remove_if(std::execution::par, v,
[](int x) { return x % 2 != 0; });
v.erase(result.begin(), result.end());
for (int x : v) {
std::cout << x << ' ';
}
std::cout << std::endl;
}
出力
2 4 6 8 10
バージョン
言語
- C++20
処理系
- Clang: ??
- GCC: 10.1.0 ✅
- ICC: ??
- Visual C++: 2019 Update 10 ✅