• Class / Function / Type

      std::
    • Header file

      <>
    • Other / All

    最終更新日時(UTC):
    が更新

    履歴 編集

    function template
    <algorithm>

    std::is_partitioned

    namespace std {
      template <class InputIterator, class Predicate>
      bool is_partitioned(InputIterator first,
                          InputIterator last,
                          Predicate pred);               // (1) C++11
    
      template <class InputIterator, class Predicate>
      constexpr bool is_partitioned(InputIterator first,
                                    InputIterator last,
                                    Predicate pred);     // (1) C++20
    
      template <class ExecutionPolicy, class ForwardIterator, class Predicate>
      bool is_partitioned(ExecutionPolicy&& exec,
                          ForwardIterator first,
                          ForwardIterator last,
                          Predicate pred);               // (2) C++17
    }
    

    概要

    イテレータ範囲[first, last)が条件によって区分化されているか判定する。

    テンプレートパラメータ制約

    • InputIteratorのvalue typeは Predicate の引数型へ変換可能でなければならない
      • つまり pred(*first) という式が有効でなければならない

    戻り値

    イテレータ範囲[first,last) が空、 または [first,last)pred によって区分化されているなら true 、そうでなければ false を返す。

    つまり、pred を満たす全ての要素が、pred を満たさない全ての要素より前に出現するなら true を返す。

    計算量

    線形時間。最大で last - firstpred が適用される。

    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    int main()
    {
      std::vector<int> v = {1, 2, 3, 4, 5};
    
      auto pred = [](int x) { return x % 2 == 0; };
    
      // 偶数グループと奇数グループに分ける
      std::partition(v.begin(), v.end(), pred);
    
      std::for_each(v.begin(), v.end(), [](int x) {
       std::cout << x << std::endl;
      });
    
      // 偶数グループと奇数グループに分かれているか
      if (std::is_partitioned(v.begin(), v.end(), pred)) {
        std::cout << "partitioned" << std::endl;
      }
      else {
        std::cout << "not partitioned" << std::endl;
      }
    }
    

    出力

    4
    2
    3
    1
    5
    partitioned
    

    実装例

    template <class InputIterator, class Predicate>
    bool is_partitioned(InputIterator first, InputIterator last, Predicate pred)
    {
      first = std::find_if_not(first, last, pred);
      return (first == last) || std::none_of(++first, last, pred);
    }
    

    バージョン

    言語

    • C++11

    処理系

    参照