• Class / Function / Type

      std::
    • Header file

      <>
    • Other / All

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

    履歴 編集

    function template
    <algorithm>

    std::ranges::minmax

    namespace std::ranges {
      template <class T,
                class Proj = identity,
                indirect_strict_weak_order<projected<const T*, Proj>> Comp = ranges::less>
      constexpr minmax_result<const T&>
        minmax(const T& a,
               const T& b,
               Comp comp = {},
               Proj proj = {}); // (1) C++20
    
      template <copyable T,
                class Proj = identity,
                indirect_strict_weak_order<projected<const T*, Proj>> Comp = ranges::less>
      constexpr minmax_result<T>
        minmax(initializer_list<T> r,
               Comp comp = {},
               Proj proj = {}); // (2) C++20
    
      template <input_range R,
                class Proj = identity,
                indirect_strict_weak_order<projected<iterator_t<R>, Proj>> Comp = ranges::less>
        requires indirectly_copyable_storable<iterator_t<R>, range_value_t<R>*>
      constexpr minmax_result<range_value_t<R>>
        minmax(R&& r,
               Comp comp = {},
               Proj proj = {}); // (3) C++20
    }
    

    概要

    同じ型の2つの値、もしくは範囲によるN個の値のうち、最小値と最大値の組を取得する。

    • (1): 2つの値を指定する
    • (2): 初期化子リストを指定する
    • (3): Rangeを指定する

    戻り値

    minmax_result {
      .min = 最小値,
      .max = 最大値,
    }
    

    それぞれ、比較 invoke(comp,invoke(proj, *i),invoke(proj, *j)) によって判断された最初の値となる。

    計算量

    • 2値比較バージョンは1操作。
    • 範囲バージョンは高々(3/2) * t.size()回の述語適用。

    #include <array>
    #include <cassert>
    #include <algorithm>
    #include <functional>
    
    int main()
    {
      const auto result1 = std::ranges::minmax(2, 3);
      assert(result1.min == 2 && result1.max == 3);
    
      const auto result2 = std::ranges::minmax(2, 3, std::ranges::greater());
      assert(result2.min == 3 && result2.max == 2);
    
      constexpr auto result3 = std::ranges::minmax({1, 2, 3});
      static_assert(result3.min == 1 && result3.max == 3);
    
      constexpr std::array<int, 3> a = {1, 2, 3};
    
      constexpr auto result4 = std::ranges::minmax(a, std::ranges::greater());
      static_assert(result4.min == 3 && result4.max == 1);
    }
    

    出力

    バージョン

    言語

    • C++20

    処理系

    参照