命名空间
变体
操作

std::is_partitioned

来自 cppreference.cn
< cpp‎ | 算法
 
 
算法库
受约束算法和范围上的算法 (C++20)
受约束算法,例如 ranges::copy, ranges::sort, ...
执行策略 (C++17)
排序和相关操作
划分操作
is_partitioned
(C++11)

排序操作
二分搜索操作
(在划分的范围上)
集合操作(在已排序范围上)
合并操作(在已排序范围上)
堆操作
最小值/最大值操作
(C++11)
(C++17)
字典序比较操作
排列操作
C 库
数值操作
未初始化内存上的操作
 
定义于头文件 <algorithm>
template< class InputIt, class UnaryPred >
bool is_partitioned( InputIt first, InputIt last, UnaryPred p );
(1) (自 C++11 起)
(constexpr 自 C++20 起)
template< class ExecutionPolicy, class ForwardIt, class UnaryPred >

bool is_partitioned( ExecutionPolicy&& policy,

                     ForwardIt first, ForwardIt last, UnaryPred p );
(2) (自 C++17 起)
1) 检查范围 [firstlast) 是否通过谓词 p 划分:所有满足 p 的元素都出现在所有不满足的元素之前。
2)(1) 相同,但根据 policy 执行。
仅当满足以下所有条件时,此重载才参与重载决议

std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>true

(直到 C++20)

std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>true

(自 C++20 起)

目录

[编辑] 参数

first, last - 定义要检查的元素范围的迭代器对
policy - 要使用的执行策略
p - 一元谓词,对于预期在范围开始处找到的元素,返回 ​true

对于 InputIt 的值类型 VT 的每个参数 v(可能是 const),表达式 p(v) 必须可转换为 bool,无论值类别如何,并且不得修改 v。因此,不允许使用 VT& 的参数类型,也不允许使用 VT,除非对于 VT,移动等同于复制(自 C++11 起)。 ​

类型要求
-
InputIt 必须满足 LegacyInputIterator 的要求。
-
ForwardIt 必须满足 LegacyForwardIterator 的要求,并且其值类型必须可转换为 UnaryPred 的参数类型。
-
UnaryPred 必须满足 Predicate 的要求。

[编辑] 返回值

如果 [firstlast) 的元素 e 相对于表达式 p(e)划分的,则返回 true。否则返回 false

[编辑] 复杂度

最多 std::distance(first, last)p 的应用。

[编辑] 异常

带有名为 ExecutionPolicy 的模板参数的重载按如下方式报告错误

  • 如果作为算法一部分调用的函数的执行抛出异常,并且 ExecutionPolicy标准策略之一,则调用 std::terminate。对于任何其他 ExecutionPolicy,行为是实现定义的。
  • 如果算法无法分配内存,则抛出 std::bad_alloc

[编辑] 可能的实现

template<class InputIt, class UnaryPred>
bool is_partitioned(InputIt first, InputIt last, UnaryPred p)
{
    for (; first != last; ++first)
        if (!p(*first))
            break;
    for (; first != last; ++first)
        if (p(*first))
            return false;
    return true;
}

[编辑] 示例

#include <algorithm>
#include <array>
#include <iostream>
 
int main()
{
    std::array<int, 9> v {1, 2, 3, 4, 5, 6, 7, 8, 9};
 
    auto is_even = [](int i) { return i % 2 == 0; };
    std::cout.setf(std::ios_base::boolalpha);
    std::cout << std::is_partitioned(v.begin(), v.end(), is_even) << ' ';
 
    std::partition(v.begin(), v.end(), is_even);
    std::cout << std::is_partitioned(v.begin(), v.end(), is_even) << ' ';
 
    std::reverse(v.begin(), v.end());
    std::cout << std::is_partitioned(v.cbegin(), v.cend(), is_even) << ' ';
    std::cout << std::is_partitioned(v.crbegin(), v.crend(), is_even) << '\n';
}

输出

false true false true

[编辑] 参见

将元素范围划分为两组
(函数模板) [编辑]
定位已划分范围的划分点
(函数模板) [编辑]
确定范围是否按给定谓词划分
(算法函数对象)[编辑]