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
헤더 파일에 정의됨 <algorithm>
함수 시그니처
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) (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) (C++20 이후)

[ first , last ) 범위 내의 요소들을 다음과 같이 재배열합니다:

  • nth 가 가리키는 요소는 [ first , last ) 범위가 comp proj 를 기준으로 정렬되었을 때 해당 위치에 오게 될 요소로 변경됩니다.
  • 이 새로운 nth 요소 이전의 모든 요소는 새로운 nth 요소 이후의 요소들보다 작거나 같습니다 . 즉, [ first , nth ) [ nth , last ) 범위에 있는 모든 반복자 i , j 에 대해, 표현식 std:: invoke ( comp, std:: invoke ( proj, * j ) , std:: invoke ( proj, * i ) ) false 로 평가됩니다.
  • 만약 nth == last 이면 함수는 아무런 효과가 없습니다.
1) 요소들은 주어진 이항 비교 함수 객체 comp 와 프로젝션 객체 proj 를 사용하여 비교됩니다.
2) (1) 과 동일하지만, r 를 범위로 사용하며, 마치 ranges:: begin ( r ) first 로, ranges:: end ( r ) last 로 사용하는 것과 같습니다.

이 페이지에서 설명하는 함수형 개체들은 algorithm function objects (일반적으로 niebloids 로 알려진)입니다. 즉:

목차

매개변수

first, last - 재정렬할 요소들의 범위 를 정의하는 반복자-감시자 쌍
r - 재정렬할 요소들의 범위
nth - 분할 지점을 정의하는 반복자
comp - 투영된 요소들을 비교하는 데 사용되는 비교자
proj - 요소들에 적용할 투영

반환값

1) last 와 동일한 반복자.
2) (1) 과 동일하지만, r 가 lvalue이거나 borrowed_range 타입인 경우. 그렇지 않으면 std::ranges::dangling 을 반환합니다.

복잡도

평균적으로 ranges:: distance ( first, last ) 에 선형입니다.

참고 사항

사용된 알고리즘은 일반적으로 introselect 이지만, 적절한 평균 경우 복잡도를 가진 다른 selection algorithms 도 허용됩니다.

가능한 구현

구현은 다음에서도 확인할 수 있습니다: msvc stl , libstdc++ , 그리고 libc++: (1) / (2) .

예제

#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';
}

출력:

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

참고 항목

범위에서 가장 큰 요소를 반환합니다
(알고리즘 함수 객체)
범위에서 가장 작은 요소를 반환합니다
(알고리즘 함수 객체)
요소들의 범위를 두 그룹으로 나눕니다
(알고리즘 함수 객체)
범위의 첫 N개 요소를 정렬합니다
(알고리즘 함수 객체)
주어진 요소로 분할되도록 주어진 범위를 부분적으로 정렬합니다
(함수 템플릿)