std::partition_point
來自 cppreference.com
定義於標頭檔案 <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。 對於型別為 (可能 const) |
型別要求 | ||
-ForwardIt 必須滿足 LegacyForwardIterator 的要求。 | ||
-UnaryPred 必須滿足 Predicate 的要求。 |
[編輯] 返回值
範圍 [
first,
last)
中第一分割槽末尾的迭代器,或在所有元素都滿足 p 時返回 last。
[編輯] 複雜度
給定 N 為 std::distance(first, last),謂詞 p 執行 O(log(N)) 次應用。
[編輯] 注意
此演算法是 std::lower_bound 的更通用形式,可以表示為帶有謂詞 [&](const auto& e) { return e < value; }); 的 std::partition_point
。
[編輯] 可能的實現
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) |
定位一個已劃分範圍的劃分點 (演算法函式物件) |