名稱空間
變體
操作

std::is_partitioned

來自 cppreference.com
< cpp‎ | 演算法
 
 
演算法庫
有約束演算法與針對範圍的演算法 (C++20)
有約束的演算法,例如 ranges::copyranges::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 起)
(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) 檢查 [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

對於型別為(可能是 const)VT 的每個引數 v,表示式 p(v) 必須可轉換為 bool,其中 VTInputIt 的值型別,無論值類別如何,並且不得修改 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

[編輯] 參閱

將一個範圍的元素分成兩組
(函式模板) [編輯]
定位一個已劃分範圍的劃分點
(函式模板) [編輯]
判斷一個範圍是否按給定謂詞劃分
(演算法函式物件)[編輯]