Namespaces
Variants

std::ranges:: minmax, std::ranges:: minmax_result

From cppreference.net
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy , ranges::sort , ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17) (C++11)
(C++20) (C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
Constrained algorithms
All names in this menu belong to namespace std::ranges
Non-modifying sequence operations
Modifying sequence operations
Partitioning operations
Sorting operations
Binary search operations (on sorted ranges)
Set operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Permutation operations
Fold operations
Operations on uninitialized storage
Return types
(Примечание: В данном HTML-фрагменте отсутствует текстовое содержимое для перевода - все элементы содержат только пустые теги или служебные атрибуты класса)
Определено в заголовочном файле <algorithm>
Сигнатура вызова
template < class T, class Proj = std:: identity ,

std:: indirect_strict_weak_order <
std :: projected < const T * , Proj >> Comp = ranges:: less >
constexpr ranges :: minmax_result < const T & >

minmax ( const T & a, const T & b, Comp comp = { } , Proj proj = { } ) ;
(1) (начиная с C++20)
template < std:: copyable T, class Proj = std:: identity ,

std:: indirect_strict_weak_order <
std :: projected < const T * , Proj >> Comp = ranges:: less >
constexpr ranges :: minmax_result < T >

minmax ( std:: initializer_list < T > r, Comp comp = { } , Proj proj = { } ) ;
(2) (начиная с C++20)
template < ranges:: input_range R, class Proj = std:: identity ,

std:: indirect_strict_weak_order <
std :: projected < ranges:: iterator_t < R > , Proj >> Comp = ranges:: less >
requires std:: indirectly_copyable_storable < ranges:: iterator_t < R > , ranges:: range_value_t < R > * >
constexpr ranges :: minmax_result < ranges:: range_value_t < R >>

minmax ( R && r, Comp comp = { } , Proj proj = { } ) ;
(3) (начиная с C++20)
Вспомогательные типы
template < class T >
using minmax_result = ranges:: min_max_result < T > ;
(4) (начиная с C++20)

Возвращает наименьшее и наибольшее из заданных проецируемых значений.

1) Возвращает ссылки на меньший и больший из a и b .
2) Возвращает наименьшее и наибольшее значения из списка инициализации r .
3) Возвращает наименьшее и наибольшее значения в диапазоне r .

Функциональные сущности, описанные на этой странице, являются алгоритмическими функциональными объектами (неформально известными как niebloids ), то есть:

Содержание

Параметры

a, b - значения для сравнения
r - непустой диапазон значений для сравнения
comp - применяемое к проецируемым элементам сравнение
proj - проекция, применяемая к элементам

Возвращаемое значение

1) { b, a } если, в соответствии с их соответствующими проецируемыми значениями, b меньше, чем a ; в противном случае возвращается { a, b } .
2,3) { s, l } , где s и l являются соответственно наименьшим и наибольшим значениями в r , согласно их проецируемому значению. Если несколько значений эквивалентны наименьшему и наибольшему, возвращает крайнее слева наименьшее значение и крайнее справа наибольшее значение. Если диапазон пуст (определяется с помощью ranges:: distance ( r ) ), поведение не определено.

Сложность

1) Ровно одно сравнение и два применения проекции.
2,3) Не более 3 / 2 * ranges:: distance ( r ) сравнений и вдвое больше применений проекции.

Возможная реализация

struct minmax_fn
{
    template<class T, class Proj = std::identity,
             std::indirect_strict_weak_order<
                 std::projected<const T*, Proj>> Comp = ranges::less>
    constexpr ranges::minmax_result<const T&>
         operator()(const T& a, const T& b, Comp comp = {}, Proj proj = {}) const
    {
        if (std::invoke(comp, std::invoke(proj, b), std::invoke(proj, a)))
            return {b, a};
        return {a, b};
    }
    template<std::copyable T, class Proj = std::identity,
             std::indirect_strict_weak_order<
                 std::projected<const T*, Proj>> Comp = ranges::less>
    constexpr ranges::minmax_result<T>
        operator()(std::initializer_list<T> r, Comp comp = {}, Proj proj = {}) const
    {
        auto result = ranges::minmax_element(r, std::ref(comp), std::ref(proj));
        return {*result.min, *result.max};
    }
    template<ranges::input_range R, class Proj = std::identity,
             std::indirect_strict_weak_order<
                 std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less>
    requires std::indirectly_copyable_storable<ranges::iterator_t<R>,
                                               ranges::range_value_t<R>*>
    constexpr ranges::minmax_result<ranges::range_value_t<R>>
        operator()(R&& r, Comp comp = {}, Proj proj = {}) const
    {
        auto result = ranges::minmax_element(r, std::ref(comp), std::ref(proj));
        return {std::move(*result.min), std::move(*result.max)};
    }
};
inline constexpr minmax_fn minmax;

Примечания

Для перегрузки (1) , если один из параметров является временным объектом, возвращаемая ссылка становится висячей ссылкой в конце полного выражения, содержащего вызов minmax :

int n = 1;
auto p = std::ranges::minmax(n, n + 1);
int m = p.min; // ok
int x = p.max; // неопределенное поведение
// Обратите внимание, что структурированные привязки имеют ту же проблему
auto [mm, xx] = std::ranges::minmax(n, n + 1);
xx; // неопределенное поведение

Пример

#include <algorithm>
#include <array>
#include <iostream>
#include <random>
int main()
{
    namespace ranges = std::ranges;
    constexpr std::array v{3, 1, 4, 1, 5, 9, 2, 6, 5};
    std::random_device rd;
    std::mt19937_64 generator(rd());
    std::uniform_int_distribution<> distribution(0, ranges::distance(v)); // [0..9]
    // auto bounds = ranges::minmax(distribution(generator), distribution(generator));
    // UB: висячие ссылки: bounds.min и bounds.max имеют тип `const int&`.
    const int x1 = distribution(generator);
    const int x2 = distribution(generator);
    auto bounds = ranges::minmax(x1, x2); // OK: получены ссылки на lvalues x1 и x2
    std::cout << "v[" << bounds.min << ":" << bounds.max << "]: ";
    for (int i = bounds.min; i < bounds.max; ++i)
        std::cout << v[i] << ' ';
    std::cout << '\n';
    auto [min, max] = ranges::minmax(v);
    std::cout << "smallest: " << min << ", " << "largest: " << max << '\n';
}

Возможный вывод:

v[3:9]: 1 5 9 2 6 5 
smallest: 1, largest: 9

Смотрите также

возвращает наименьшее из заданных значений
(функциональный объект алгоритма)
возвращает наибольшее из заданных значений
(функциональный объект алгоритма)
возвращает наименьший и наибольший элементы в диапазоне
(функциональный объект алгоритма)
ограничивает значение между парой граничных значений
(функциональный объект алгоритма)
(C++11)
возвращает меньший и больший из двух элементов
(шаблон функции)