名稱空間
變體
操作

std::partition_point

來自 cppreference.com
< cpp‎ | 演算法
 
 
演算法庫
有約束演算法與針對範圍的演算法 (C++20)
有約束的演算法,例如 ranges::copyranges::sort 等……
執行策略 (C++17)
排序及相關操作
劃分操作
partition_point
(C++11)

排序操作
二分搜尋操作
(於已劃分範圍上)
集合操作(於已排序範圍上)
歸併操作(於已排序範圍上)
堆操作
最小/最大值操作
(C++11)
(C++17)
字典序比較操作
排列操作
C 庫
數值操作
未初始化記憶體上的操作
 
定義於標頭檔案 <algorithm>
template< class ForwardIt, class UnaryPred >
ForwardIt partition_point( ForwardIt first, ForwardIt last, UnaryPred p );
(C++11 起)
(C++20 起為 constexpr)

檢查已分割槽範圍 [firstlast) 並定位第一分割槽末尾,即不滿足 p 的首個元素,或在所有元素都滿足 p 時返回 last

[firstlast) 中的元素 elem 未根據表示式 bool(p(elem)) 分割槽,則行為未定義。

目錄

[編輯] 引數

first, last - 定義要檢查的元素已分割槽範圍的迭代器對。
p - 一元謂詞,對範圍開頭的元素返回 ​true

對於型別為 (可能 const) VT 的每個引數 v,其中 VTForwardIt 的值型別,表示式 p(v) 必須可轉換為 bool,而無論值類別如何,並且不得修改 v。因此,不允許引數型別為 VT&,除非對於 VT 移動等同於複製,否則也不允許 VT(C++11 起)。 ​

型別要求
-
ForwardIt 必須滿足 LegacyForwardIterator 的要求。
-
UnaryPred 必須滿足 Predicate 的要求。

[編輯] 返回值

範圍 [firstlast) 中第一分割槽末尾的迭代器,或在所有元素都滿足 p 時返回 last

[編輯] 複雜度

給定 Nstd::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)
檢查一個範圍是否按升序排序
(函式模板) [編輯]
返回一個指向第一個不小於給定值的元素的迭代器
(函式模板) [編輯]
定位一個已劃分範圍的劃分點
(演算法函式物件)[編輯]