std::ranges::partition_point
| 定义于头文件 <algorithm>
|
||
| 调用签名 |
||
template< std::forward_iterator I, std::sentinel_for<I> S,
class Proj = std::identity,
std::indirect_unary_predicate<std::projected<I, Proj>> Pred >
constexpr I
partition_point( I first, S last, Pred pred, Proj proj = {} );
|
(1) | (C++20 起) |
template< ranges::forward_range R,
class Proj = std::identity,
std::indirect_unary_predicate<
std::projected<ranges::iterator_t<R>, Proj>> Pred >
constexpr ranges::borrowed_iterator_t<R>
partition_point( R&& r, Pred pred, Proj proj = {} );
|
(2) | (C++20 起) |
检查已按(如同通过 ranges::partition)划分的范围 [first, last) 或 r 并定位第一个分区的结尾,即不满足 pred 的投影后元素,或 last 如果所有投影后元素都满足 pred。
此页面上描述的函数式实体是算法函数对象(非正式地称为 niebloids),即:
参数
| first, last | - | 定义待检验元素部分有序 范围 的迭代器-哨位对 |
| r | - | 待检验的部分有序范围 |
| pred | - | 应用于投影元素的谓词 |
| proj | - | 应用于元素的投影 |
返回值
指向第一个分区末尾的迭代器,位于
[
first
,
last
)
范围内,或者当所有投影元素均满足
pred
时返回与
last
相等的迭代器。
复杂度
给定 N = ranges:: distance ( first, last ) ,执行 O(log N) 次谓词 pred 和投影 proj 的应用。
然而,如果哨兵不满足 std:: sized_sentinel_for < I > 概念要求,则迭代器递增次数为 O(N) 。
注释
该算法是
ranges::lower_bound
的更通用形式,可通过
ranges::partition_point
配合谓词
[
&
]
(
auto
const
&
e
)
{
return
std::
invoke
(
pred, e, value
)
;
}
)
;
来表达。
示例
#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::ranges::partition(v, is_even); print_seq("After partitioning, v: ", v.cbegin(), v.cend()); const auto pp = std::ranges::partition_point(v, is_even); const auto i = std::ranges::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: 2 4 6 8 5 3 7 1 9 Partition point is at 4; v[4] = 5 First partition (all even elements): 2 4 6 8 Second partition (all odd elements): 5 3 7 1 9
参见
(C++20) |
检查范围是否已排序 (算法函数对象) |
(C++20) |
使用二分查找找到第一个不小于给定值的元素 (算法函数对象) |
(C++11) |
定位已划分范围的划分点 (函数模板) |