namespace std::ranges {
template <bidirectional_iterator I,
sentinel_for<I> S,
class Proj = identity,
indirect_unary_predicate<projected<I, Proj>> Pred>
requires permutable<I>
subrange<I>
stable_partition(I first,
S last,
Pred pred,
Proj proj = {}); // (1) C++20
template <bidirectional_iterator I,
sentinel_for<I> S,
class Proj = identity,
indirect_unary_predicate<projected<I, Proj>> Pred>
requires permutable<I>
constexpr subrange<I>
stable_partition(I first,
S last,
Pred pred,
Proj proj = {}); // (1) C++26
template <bidirectional_range R,
class Proj = identity,
indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred>
requires permutable<iterator_t<R>>
borrowed_subrange_t<R>
stable_partition(R&& r,
Pred pred,
Proj proj = {}); // (2) C++20
template <bidirectional_range R,
class Proj = identity,
indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred>
requires permutable<iterator_t<R>>
constexpr borrowed_subrange_t<R>
stable_partition(R&& r,
Pred pred,
Proj proj = {}); // (2) C++26
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>
stable_partition(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>
stable_partition(Ep&& exec,
R&& r,
Pred pred,
Proj proj = {}); // (4) C++26
}
概要
与えられた範囲を相対順序を保ちながら条件によって区分化する。
- (1): イテレータ範囲を指定する
- (2): Rangeを直接指定する
- (3): (1)の並列アルゴリズム版。実行ポリシーを指定する
- (4): (2)の並列アルゴリズム版。実行ポリシーを指定する
効果
[first,last) 内にある pred を満たす全ての要素を、pred を満たさない全ての要素より前に移動させる。
戻り値
{i, last}
ただし、[first,i) 内にあるイテレータ j について pred(*j) != false を満たし、[i,last) 内にあるイテレータ k について pred(*k) == false を満たすようなイテレータ(つまり、区分化された境界を指すイテレータ)を i とする。
条件を満たす・満たさない両グループ内での要素間の相対順序は保たれる。
計算量
N = last - firstとして説明する。
- (1), (2) : 最大でN log N回 swap が行われるが、余分なメモリを使って構わないのであれば線形回数の swap になる。それに加えて、正確にN回だけ述語が適用される
例
基本的な使い方
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> v = {1, 2, 3, 4, 5};
// 偶数グループと奇数グループに分ける
std::ranges::stable_partition(v, [](int x) { return x % 2 == 0; });
for (int x : v) {
std::cout << x << std::endl;
}
}
出力
2
4
1
3
5
並列アルゴリズムの例 (C++26)
#include <iostream>
#include <vector>
#include <algorithm>
#include <execution>
int main()
{
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8};
// 並列に相対順序を保ちながら偶数グループと奇数グループに分ける
std::ranges::stable_partition(std::execution::par, v, [](int x) { return x % 2 == 0; });
for (int x : v) {
std::cout << x << ' ';
}
std::cout << std::endl;
}
出力
2 4 6 8 1 3 5 7
バージョン
言語
- C++20
処理系
- Clang: ??
- GCC: 10.1.0 ✅
- ICC: ??
- Visual C++: 2019 Update 10 ✅
参照
- N4861 25 Algorithms library
- P2562R1
constexprStable Sorting- C++26から
constexprに対応した
- C++26から
- P3179R9 C++ parallel range algorithms