namespace std::ranges {
template <input_iterator I,
sentinel_for<I> S,
class T,
class Proj = identity,
indirect_unary_predicate<projected<I, Proj>> Pred>
requires indirectly_writable<I, const T&>
constexpr I
replace_if(I first,
S last,
Pred pred,
const T& new_value,
Proj proj = {}); // (1) C++20
template <input_range R,
class T,
class Proj = identity,
indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred>
requires indirectly_writable<iterator_t<R>, const T&>
constexpr borrowed_iterator_t<R>
replace_if(R&& r,
Pred pred,
const T& new_value,
Proj proj = {}); // (2) C++20
template <execution-policy Ep,
random_access_iterator I,
sized_sentinel_for<I> S,
class T,
class Proj = identity,
indirect_unary_predicate<projected<I, Proj>> Pred>
requires indirectly_writable<I, const T&>
I replace_if(Ep&& exec,
I first,
S last,
Pred pred,
const T& new_value,
Proj proj = {}); // (3) C++26
template <execution-policy Ep,
sized-random-access-range R,
class T,
class Proj = identity,
indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred>
requires indirectly_writable<iterator_t<R>, const T&>
borrowed_iterator_t<R>
replace_if(Ep&& exec,
R&& r,
Pred pred,
const T& new_value,
Proj proj = {}); // (4) C++26
}
概要
条件を満たす要素を指定された値に置き換える。
- (1): イテレータ範囲を指定する
- (2): Rangeを直接指定する
- (3): (1)の並列アルゴリズム版。実行ポリシーを指定する
- (4): (2)の並列アルゴリズム版。実行ポリシーを指定する
効果
[first,last) 内のイテレータ i について、pred(*i) != false であるものは *i = new_value という式によってに置き換えられる。
戻り値
last
計算量
正確に last - first 回の述語の適用を行う。
備考
- (1), (2) :
- C++26 : 引数として波カッコ初期化
{}を受け付ける
std::vector<T> v; std::ranges::replace_if(v, pred, {a, b});
- C++26 : 引数として波カッコ初期化
例
基本的な使い方
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = { 3,1,2,1,2 };
// 奇数の要素を全部 10 に置き換える
std::ranges::replace_if(v, [](int x) { return x % 2 != 0; }, 10);
for (int x : v) {
std::cout << x << ",";
}
}
出力
10,10,2,10,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};
// 並列に奇数を全て0に置き換える
std::ranges::replace_if(std::execution::par, v,
[](int x) { return x % 2 != 0; }, 0);
for (int x : v) {
std::cout << x << ' ';
}
std::cout << std::endl;
}
出力
0 2 0 4 0 6 0 8 0 10
バージョン
言語
- C++20
処理系
- Clang: ??
- GCC: 10.1.0 ✅
- ICC: ??
- Visual C++: 2019 Update 10 ✅
参照
- N4861 25 Algorithms library
- P2248R8 Enabling list-initialization for algorithms
- C++26で波カッコ初期化 (リスト初期化) に対応した
- P3179R9 C++ parallel range algorithms