std:: partition_point
|
定义于头文件
<algorithm>
|
||
|
template
<
class
ForwardIt,
class
UnaryPred
>
ForwardIt partition_point ( ForwardIt first, ForwardIt last, UnaryPred p ) ; |
(C++11 起)
(C++20 起为 constexpr) |
|
检查已分区的范围
[
first
,
last
)
并定位第一个分区的结束位置,即首个不满足
p
的元素,若所有元素均满足
p
则返回
last
。
如果范围
[
first
,
last
)
中的元素
elem
未按表达式
bool
(
p
(
elem
)
)
进行
分区
,则行为未定义。
目录 |
参数
| first, last | - | 定义待检验元素分区 范围 的迭代器对 |
| p | - |
一元谓词,对位于范围起始处的元素返回
true
。
表达式
p
(
v
)
必须对每个类型为(可能 const 的)
|
| 类型要求 | ||
-
ForwardIt
必须满足
LegacyForwardIterator
的要求。
|
||
-
UnaryPred
必须满足
Predicate
的要求。
|
||
返回值
指向第一个分区末尾的迭代器,位于
[
first
,
last
)
范围内,若所有元素均满足
p
则返回
last
。
复杂度
给定 \(\scriptsize N\) N 为 std:: distance ( first, last ) ,执行 \(\scriptsize O(log(N))\) O(log(N)) 次谓词 p 的应用。
注释
该算法是
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)
|
定位已分区范围的分区点
(算法函数对象) |