Namespaces
Variants

std::ranges:: nth_element

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
Definido en el encabezado <algorithm>
Firma de llamada
template < std:: random_access_iterator I, std:: sentinel_for < I > S,

class Comp = ranges:: less , class Proj = std:: identity >
requires std:: sortable < I, Comp, Proj >
constexpr I

nth_element ( I first, I nth, S last, Comp comp = { } , Proj proj = { } ) ;
(1) (desde C++20)
template < ranges:: random_access_range R,

class Comp = ranges:: less , class Proj = std:: identity >
requires std:: sortable < iterator_t < R > , Comp, Proj >
constexpr ranges:: borrowed_iterator_t < R >

nth_element ( R && r, iterator_t < R > nth, Comp comp = { } , Proj proj = { } ) ;
(2) (desde C++20)

Reordena los elementos en [ first , last ) de tal manera que:

  • El elemento apuntado por nth se cambia al elemento que ocurriría en esa posición si [ first , last ) estuviera ordenado con respecto a comp y proj .
  • Todos los elementos anteriores a este nuevo elemento nth son menores o iguales que los elementos posteriores al nuevo nth . Es decir, para todo iterador i , j en los rangos [ first , nth ) , [ nth , last ) respectivamente, la expresión std:: invoke ( comp, std:: invoke ( proj, * j ) , std:: invoke ( proj, * i ) ) evalúa a false .
  • Si nth == last entonces la función no tiene efecto.
1) Los elementos se comparan utilizando el objeto de función de comparación binaria proporcionado comp y el objeto de proyección proj .
2) Igual que (1) , pero utiliza r como el rango, como si se usara ranges:: begin ( r ) como first y ranges:: end ( r ) como last .

Las entidades similares a funciones descritas en esta página son algorithm function objects (conocidas informalmente como niebloids ), es decir:

Contenidos

Parámetros

first, last - el par iterador-centinela que define el rango de elementos a reordenar
r - el rango de elementos a reordenar
nth - el iterador que define el punto de partición
comp - comparador utilizado para comparar los elementos proyectados
proj - proyección a aplicar a los elementos

Valor de retorno

1) Un iterador igual a last .
2) Igual que (1) si r es un lvalue o de tipo borrowed_range . De lo contrario, retorna std::ranges::dangling .

Complejidad

Lineal en ranges:: distance ( first, last ) en promedio.

Notas

El algoritmo utilizado es típicamente introselect aunque se permiten otros selection algorithms con complejidad promedio adecuada.

Implementación posible

Consulte también la implementación en msvc stl , libstdc++ , y libc++: (1) / (2) .

Ejemplo

#include <algorithm>
#include <array>
#include <functional>
#include <iostream>
#include <ranges>
#include <string_view>
void print(std::string_view rem, std::ranges::input_range auto const& a)
{
    for (std::cout << rem; const auto e : a)
        std::cout << e << ' ';
    std::cout << '\n';
}
int main()
{
    std::array v{5, 6, 4, 3, 2, 6, 7, 9, 3};
    print("Before nth_element: ", v);
    std::ranges::nth_element(v, v.begin() + v.size() / 2);
    print("After nth_element:  ", v);
    std::cout << "The median is: " << v[v.size() / 2] << '\n';
    std::ranges::nth_element(v, v.begin() + 1, std::greater<int>());
    print("After nth_element:  ", v);
    std::cout << "The second largest element is: " << v[1] << '\n';
    std::cout << "The largest element is: " << v[0] << "\n\n";
    using namespace std::literals;
    std::array names
    {
        "Diva"sv, "Cornelius"sv, "Munro"sv, "Rhod"sv,
        "Zorg"sv, "Korben"sv, "Bender"sv, "Leeloo"sv,
    };
    print("Before nth_element: ", names);
    auto fifth_element{std::ranges::next(names.begin(), 4)};
    std::ranges::nth_element(names, fifth_element);
    print("After nth_element:  ", names);
    std::cout << "The 5th element is: " << *fifth_element << '\n';
}

Salida:

Before nth_element: 5 6 4 3 2 6 7 9 3 
After nth_element:  2 3 3 4 5 6 6 7 9 
The median is: 5
After nth_element:  9 7 6 6 5 4 3 3 2 
The second largest element is: 7
The largest element is: 9
Before nth_element: Diva Cornelius Munro Rhod Zorg Korben Bender Leeloo 
After nth_element:  Diva Cornelius Bender Korben Leeloo Rhod Munro Zorg 
The 5th element is: Leeloo

Véase también

devuelve el elemento más grande en un rango
(objeto función de algoritmo)
devuelve el elemento más pequeño en un rango
(objeto función de algoritmo)
divide un rango de elementos en dos grupos
(objeto función de algoritmo)
ordena los primeros N elementos de un rango
(objeto función de algoritmo)
ordena parcialmente el rango dado asegurando que está particionado por el elemento dado
(plantilla de función)