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 或 last 如果所有元素均满足 p。
如果元素 elem 位于 [first, last) 未按 划分 对表达式 bool(p(elem)),则行为未定义。
参数
| first, last | - | 定义待检验元素分区 范围 的迭代器对 |
| p | - |
一元谓词,对位于范围起始处的元素返回
true
。
表达式
p
(
v
)
必须对每个类型为(可能 const 的)
|
| 类型要求 | ||
-
ForwardIt
必须满足
LegacyForwardIterator
的要求。
|
||
-
UnaryPred
必须满足
Predicate
的要求。
|
||
返回值
指向第一个分区末尾的迭代器,位于
[
first
,
last
)
范围内,若所有元素均满足
p
则返回
last
。
复杂度
给定 N 为 std:: distance ( first, last ) ,执行 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++20)(C++20)(C++20) |
|
(C++11) |
检查范围是否已排序 (函数模板 & 算法函数对象) |
(C++20) |
|
| 使用二分查找找到第一个不小于给定值的元素 (函数模板 & 算法函数对象) | |
(C++20) |
|
(C++20) |
定位已划分范围的划分点 (算法函数对象) |