Namespaces
Variants

std::partition_point

来自 zh.cppreference.net
 
 
算法库
受约束算法和范围算法 (C++20)
受约束算法,例如 ranges::copy, ranges::sort, ...
排序和相关操作
划分操作
(C++11)    

排序操作
二分查找操作
(在划分范围上)
集合操作(在排序范围上)
合并操作(在排序范围上)
堆操作
最小/最大操作
(C++11)
(C++17)
字典序比较操作
排列操作


 
定义于头文件 <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 的) VT 的参数 v 可转换为 bool ,其中 VT 是 ForwardIt 的值类型,且与 值类别 无关,同时不得修改 v 。因此,形参类型 VT & 是不允许的 , VT 也不允许,除非对于 VT 类型移动操作等价于拷贝操作 (C++11 起) 。 ​

类型要求
-
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)
检查范围是否已排序
(函数模板 & 算法函数对象)
使用二分查找找到第一个不小于给定值的元素
(函数模板 & 算法函数对象)
定位已划分范围的划分点
(算法函数对象)