std::ranges::partition_point
定义于头文件 <algorithm> |
||
调用签名 |
||
template< std::forward_iterator I, std::sentinel_for<I> S, class Proj = std::identity, |
(1) | (since C++20) |
template< ranges::forward_range R, class Proj = std::identity, |
(2) | (since C++20) |
检查已划分(如同通过 ranges::partition)的范围 [
first,
last)
或 r,并定位第一个划分的末尾,即不满足 pred 的投影元素,如果所有投影元素都满足 pred,则定位到 last。
此页面上描述的类似函数的实体是 算法函数对象(非正式地称为 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
的更通用形式,可以使用谓词 [&](auto const& e) { return std::invoke(pred, e, value); }); 用 ranges::partition_point
表示。
[编辑] 示例
#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) |
定位已划分范围的划分点 (函数模板) |