Namespaces
Variants

std::is_partitioned

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

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


 
定义于头文件 <algorithm>
template< class InputIt, class UnaryPred >
bool is_partitioned( InputIt first, InputIt last, UnaryPred p );
(1) (C++11 起)
(C++20 起 constexpr)
template< class ExecutionPolicy, class ForwardIt, class UnaryPred >
bool is_partitioned( ExecutionPolicy&& policy,
                     ForwardIt first, ForwardIt last, UnaryPred p );
(2) (C++17 起)
1) 检查范围 [first, last) 是否已按谓词 p 划分:所有满足 p 的元素出现在所有不满足的元素之前。
2) 同 (1),但按 policy 执行。
此重载仅当下列表达式的值为 true 时参与重载决议:

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

(C++20 前)

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

(C++20 起)

参数

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

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

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

返回值

true 如果范围 e 中的元素 [first, last) 已根据表达式 进行划分p(e),则为 false,否则为

。

复杂度std::distance(first, last) 最多 p 次应用

。

异常ExecutionPolicy 带有模板参数名为

  • 的重载会按如下方式报告错误: ExecutionPolicy 如果作为算法一部分调用的函数执行时抛出异常,且 是标准策略之一,则调用 std::terminateExecutionPolicy。对于任何其他
  • ,行为由实现定义。 如果算法无法分配内存,则抛出 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

参阅

将范围中的元素分为两组
(函数模板 & 算法函数对象)
定位已划分范围的划分点
(函数模板 & 算法函数对象)
确定范围是否由给定谓词划分
(算法函数对象)