std::ranges::partition_point
定義於標頭檔案 <algorithm> |
||
呼叫簽名 (Call signature) |
||
template< std::forward_iterator I, std::sentinel_for<I> S, class Proj = std::identity, |
(1) | (C++20 起) |
template< ranges::forward_range R, class Proj = std::identity, |
(2) | (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),執行謂詞 pred 和投影 proj 的 O(log N) 次應用。
然而,如果哨兵不模擬 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) |
定位一個已劃分範圍的劃分點 (函式模板) |