std:: partition_point
|
定義先ヘッダ
<algorithm>
|
||
|
template
<
class
ForwardIt,
class
UnaryPred
>
ForwardIt partition_point ( ForwardIt first, ForwardIt last, UnaryPred p ) ; |
(C++11以降)
(constexpr C++20以降) |
|
分割された範囲
[
first
,
last
)
を調べ、最初の分割の終端、すなわち
p
を満たさない最初の要素、または全ての要素が
p
を満たす場合は
last
を特定します。
[
first
,
last
)
の要素
elem
が式
bool
(
p
(
elem
)
)
に関して
区分化
されていない場合、動作は未定義です。
目次 |
パラメータ
| first, last | - | パーティション分割された要素の範囲を定義するイテレータのペア |
| p | - |
範囲の先頭に見つかった要素に対して
true
を返す単項述語
式
p
(
v
)
は、
|
| 型要件 | ||
-
ForwardIt
は
LegacyForwardIterator
の要件を満たさなければならない
|
||
-
UnaryPred
は
Predicate
の要件を満たさなければならない
|
||
戻り値
範囲
[
first
,
last
)
内の最初のパーティションの終端を指すイテレータ、または全ての要素が
p
を満たす場合は
last
を返す。
計算量
\(\scriptsize N\) N が std:: distance ( first, last ) として与えられたとき、述語 p の適用を \(\scriptsize O(log(N))\) O(log(N)) 回実行します。
注記
このアルゴリズムは
std::lower_bound
のより一般化された形式であり、
std::partition_point
と述語
[
&
]
(
const
auto
&
e
)
{
return
e
<
value
;
}
)
;
を用いて表現できます。
実装例
template<class ForwardIt, class UnaryPred> constexpr //< since C++20 ForwardIt partition_point(ForwardIt first, ForwardIt last, UnaryPred p) { for (auto length = std::distance(first, last); 0 < length; ) { auto half = length / 2; auto middle = std::next(first, half); if (p(*middle)) { first = std::next(middle); length -= (half + 1); } else length = half; } return first; } |
例
#include <algorithm> #include <array> #include <iostream> #include <iterator> auto print_seq = [](auto rem, auto first, auto last) { for (std::cout << rem; first != last; std::cout << *first++ << ' ') {} std::cout << '\n'; }; int main() { std::array v{1, 2, 3, 4, 5, 6, 7, 8, 9}; auto is_even = [](int i) { return i % 2 == 0; }; std::partition(v.begin(), v.end(), is_even); print_seq("After partitioning, v: ", v.cbegin(), v.cend()); const auto pp = std::partition_point(v.cbegin(), v.cend(), is_even); const auto i = std::distance(v.cbegin(), pp); std::cout << "Partition point is at " << i << "; v[" << i << "] = " << *pp << '\n'; print_seq("First partition (all even elements): ", v.cbegin(), pp); print_seq("Second partition (all odd elements): ", pp, v.cend()); }
出力例:
After partitioning, v: 8 2 6 4 5 3 7 1 9 Partition point is at 4; v[4] = 5 First partition (all even elements): 8 2 6 4 Second partition (all odd elements): 5 3 7 1 9
関連項目
|
(C++11)
|
特定の条件を満たす最初の要素を見つける
(関数テンプレート) |
|
(C++11)
|
範囲が昇順にソートされているかどうかをチェックする
(関数テンプレート) |
|
指定された値より
小さくない
最初の要素へのイテレータを返す
(関数テンプレート) |
|
|
(C++20)
|
分割された範囲の分割点を特定する
(アルゴリズム関数オブジェクト) |