Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/algorithm/ranges/nth element"

From cppreference.com
< cpp‎ | algorithm‎ | ranges
m (fmt)
 
(3 intermediate revisions by 2 users not shown)
Line 2: Line 2:
 
{{cpp/algorithm/ranges/navbar}}
 
{{cpp/algorithm/ranges/navbar}}
 
{{dcl begin}}
 
{{dcl begin}}
{{dcl header | algorithm}}
+
{{dcl header|algorithm}}
{{dcl h | Call signature}}
+
{{dcl h|Call signature}}
{{dcl | num=1 | since=c++20 |1=
+
{{dcl|num=1|since=c++20|1=
 
template< std::random_access_iterator I, std::sentinel_for<I> S,
 
template< std::random_access_iterator I, std::sentinel_for<I> S,
 
           class Comp = ranges::less, class Proj = std::identity >
 
           class Comp = ranges::less, class Proj = std::identity >
 
requires std::sortable<I, Comp, Proj>
 
requires std::sortable<I, Comp, Proj>
 
constexpr I
 
constexpr I
  nth_element( I first, I nth, S last, Comp comp = {}, Proj proj = {} );
+
    nth_element( I first, I nth, S last, Comp comp = {}, Proj proj = {} );
 
}}
 
}}
{{dcl | num=2 | since=c++20 |1=
+
{{dcl|num=2|since=c++20|1=
 
template< ranges::random_access_range R,
 
template< ranges::random_access_range R,
 
           class Comp = ranges::less, class Proj = std::identity >
 
           class Comp = ranges::less, class Proj = std::identity >
 
requires std::sortable<iterator_t<R>, Comp, Proj>
 
requires std::sortable<iterator_t<R>, Comp, Proj>
 
constexpr ranges::borrowed_iterator_t<R>
 
constexpr ranges::borrowed_iterator_t<R>
  nth_element( R&& r, iterator_t<R> nth, Comp comp = {}, Proj proj = {} );
+
    nth_element( R&& r, iterator_t<R> nth, Comp comp = {}, Proj proj = {} );
 
}}
 
}}
 
{{dcl end}}
 
{{dcl end}}
  
Reorders the elements in {{tt|[first, last)}} such that:
+
Reorders the elements in {{range|first|last}} such that:
* The element pointed at by {{tt|nth}} is changed to whatever element would occur in that position if {{tt|[first, last)}} were sorted with respect to {{tt|comp}} and {{tt|proj}}.
+
* The element pointed at by {{c|nth}} is changed to whatever element would occur in that position if {{range|first|last}} were sorted with respect to {{c|comp}} and {{c|proj}}.
* All of the elements before this new {{ttb|nth}} element are ''less than or equal to'' the elements after the new {{tt|nth}} element. That is, for every iterator ''i'', ''j'' in the ranges {{tt|[first, nth)}}, {{tt|[nth, last)}} respectively, the expression {{c|std::invoke(comp, std::invoke(proj, *j), std::invoke(proj, *i))}} evaluates to {{c|false}}.
+
* All of the elements before this new {{ttb|nth}} element are ''less than or equal to'' the elements after the new {{c|nth}} element. That is, for every iterator ''i'', ''j'' in the ranges {{range|first|nth}}, {{range|nth|last}} respectively, the expression {{c|std::invoke(comp, std::invoke(proj, *j), std::invoke(proj, *i))}} evaluates to {{c|false}}.
 
* If {{c|1=nth == last}} then the function has no effect.
 
* If {{c|1=nth == last}} then the function has no effect.
  
@1@ Elements are compared using the given binary comparison function object {{tt|comp}} and projection object {{tt|proj}}.
+
@1@ Elements are compared using the given binary comparison function object {{c|comp}} and projection object {{c|proj}}.
  
@2@ Same as {{v|1}}, but uses {{tt|r}} as the range, as if using {{c|ranges::begin(r)}} as {{tt|first}} and {{c|ranges::end(r)}} as {{tt|last}}.
+
@2@ Same as {{v|1}}, but uses {{c|r}} as the range, as if using {{c|ranges::begin(r)}} as {{c|first}} and {{c|ranges::end(r)}} as {{c|last}}.
  
 
{{cpp/ranges/niebloid}}
 
{{cpp/ranges/niebloid}}
Line 33: Line 33:
 
===Parameters===
 
===Parameters===
 
{{par begin}}
 
{{par begin}}
{{par | first, last | the range of elements to reorder}}
+
{{par|first, last|the range of elements to reorder}}
{{par | r           | the range of elements to reorder}}
+
{{par|r|the range of elements to reorder}}
{{par | nth         | the iterator defining the partition point}}
+
{{par|nth|the iterator defining the partition point}}
{{par | comp       | comparator used to compare the projected elements}}
+
{{par|comp|comparator used to compare the projected elements}}
{{par | proj       | projection to apply to the elements}}
+
{{par|proj|projection to apply to the elements}}
 
{{par end}}
 
{{par end}}
  
 
===Return value===
 
===Return value===
@1@ An iterator equal to {{tt|last}}.
+
@1@ An iterator equal to {{c|last}}.
@2@ Same as {{v|1}} if {{tt|r}} is an lvalue or of a {{lconcept|borrowed_range}} type. Otherwise returns {{lc|std::ranges::dangling}}.
+
@2@ Same as {{v|1}} if {{c|r}} is an lvalue or of a {{lconcept|borrowed_range}} type. Otherwise returns {{lc|std::ranges::dangling}}.
  
 
===Complexity===
 
===Complexity===
Line 51: Line 51:
  
 
===Possible implementation===
 
===Possible implementation===
See also the implementation in [https://github.com/microsoft/STL/blob/e745bad3b1d05b5b19ec652d68abb37865ffa454/stl/inc/algorithm#L8429-L8499 MSVC STL] and [https://github.com/gcc-mirror/gcc/blob/54258e22b0846aaa6bd3265f592feb161eecda75/libstdc%2B%2B-v3/include/bits/ranges_algo.h#L2052-L2080 libstdc++].
+
See also the implementation in [https://github.com/microsoft/STL/blob/e97bb2b50a12816ce68cc5147b7a3a21fb68bfa3/stl/inc/algorithm#L8896-L8969 msvc stl], [https://github.com/gcc-mirror/gcc/blob/a87819b8f1b890d36a3f05bd9de80be20e9525dd/libstdc%2B%2B-v3/include/bits/ranges_algo.h#L2016-L2044 libstdc++], and libc++: [https://github.com/llvm/llvm-project/blob/ed2d3644abee9535eb07333beb1562a651001281/libcxx/include/__algorithm/ranges_nth_element.h (1)] / [https://github.com/llvm/llvm-project/blob/ed2d364/libcxx/include/__algorithm/nth_element.h (2)].
  
 
===Example===
 
===Example===
{{example | code=
+
{{example
 +
|code=
 
#include <algorithm>
 
#include <algorithm>
 
#include <array>
 
#include <array>
Line 66: Line 67:
 
     for (std::cout << rem; const auto e : a)
 
     for (std::cout << rem; const auto e : a)
 
         std::cout << e << ' ';
 
         std::cout << e << ' ';
     std::cout << "\n";
+
     std::cout << '\n';
 
}
 
}
  
Line 74: Line 75:
 
     print("Before nth_element: ", v);
 
     print("Before nth_element: ", v);
  
     std::ranges::nth_element(v, v.begin() + v.size()/2);
+
     std::ranges::nth_element(v, v.begin() + v.size() / 2);
 
     print("After nth_element:  ", v);
 
     print("After nth_element:  ", v);
     std::cout << "The median is: " << v[v.size()/2] << '\n';
+
     std::cout << "The median is: " << v[v.size() / 2] << '\n';
  
 
     std::ranges::nth_element(v, v.begin() + 1, std::greater<int>());
 
     std::ranges::nth_element(v, v.begin() + 1, std::greater<int>());
Line 82: Line 83:
 
     std::cout << "The second largest element is: " << v[1] << '\n';
 
     std::cout << "The second largest element is: " << v[1] << '\n';
 
     std::cout << "The largest element is: " << v[0] << "\n\n";
 
     std::cout << "The largest element is: " << v[0] << "\n\n";
 
  
 
     using namespace std::literals;
 
     using namespace std::literals;
     std::array names {
+
     std::array names
 +
    {
 
         "Diva"sv, "Cornelius"sv, "Munro"sv, "Rhod"sv,
 
         "Diva"sv, "Cornelius"sv, "Munro"sv, "Rhod"sv,
 
         "Zorg"sv, "Korben"sv, "Bender"sv, "Leeloo"sv,
 
         "Zorg"sv, "Korben"sv, "Bender"sv, "Leeloo"sv,
 
     };
 
     };
 
     print("Before nth_element: ", names);
 
     print("Before nth_element: ", names);
     auto fifth_element {std::ranges::next(names.begin(), 4)};
+
     auto fifth_element{std::ranges::next(names.begin(), 4)};
 
     std::ranges::nth_element(names, fifth_element);
 
     std::ranges::nth_element(names, fifth_element);
 
     print("After nth_element:  ", names);
 
     print("After nth_element:  ", names);
 
     std::cout << "The 5th element is: " << *fifth_element << '\n';
 
     std::cout << "The 5th element is: " << *fifth_element << '\n';
 
}
 
}
| output=
+
|output=
 
Before nth_element: 5 6 4 3 2 6 7 9 3  
 
Before nth_element: 5 6 4 3 2 6 7 9 3  
 
After nth_element:  2 3 3 4 5 6 6 7 9  
 
After nth_element:  2 3 3 4 5 6 6 7 9  
Line 110: Line 111:
 
===See also===
 
===See also===
 
{{dsc begin}}
 
{{dsc begin}}
{{dsc inc | cpp/algorithm/ranges/dsc max_element}}
+
{{dsc inc|cpp/algorithm/ranges/dsc max_element}}
{{dsc inc | cpp/algorithm/ranges/dsc min_element}}
+
{{dsc inc|cpp/algorithm/ranges/dsc min_element}}
{{dsc inc | cpp/algorithm/ranges/dsc partition}}
+
{{dsc inc|cpp/algorithm/ranges/dsc partition}}
{{dsc inc | cpp/algorithm/ranges/dsc partial_sort}}
+
{{dsc inc|cpp/algorithm/ranges/dsc partial_sort}}
{{dsc inc | cpp/algorithm/dsc nth_element}}
+
{{dsc inc|cpp/algorithm/dsc nth_element}}
 
{{dsc end}}
 
{{dsc end}}
  
 
{{langlinks|de|es|fr|it|ja|pt|ru|zh}}
 
{{langlinks|de|es|fr|it|ja|pt|ru|zh}}

Latest revision as of 23:34, 22 September 2023

 
 
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
(C++11)                (C++11)(C++11)

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
(C++11)
(C++17)
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
       
     
nth_element
Binary search operations (on sorted ranges)
       
       
Set operations (on sorted ranges)
Heap operations
Minimum/maximum operations
       
       
Permutation operations
Fold operations
Numeric operations
(C++23)            
Operations on uninitialized storage
Return types
 
Defined in header <algorithm>
Call signature
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) (since 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) (since C++20)

Reorders the elements in [firstlast) such that:

  • The element pointed at by nth is changed to whatever element would occur in that position if [firstlast) were sorted with respect to comp and proj.
  • All of the elements before this new nth element are less than or equal to the elements after the new nth element. That is, for every iterator i, j in the ranges [firstnth), [nthlast) respectively, the expression std::invoke(comp, std::invoke(proj, *j), std::invoke(proj, *i)) evaluates to false.
  • If nth == last then the function has no effect.
1) Elements are compared using the given binary comparison function object comp and projection object proj.
2) Same as (1), but uses r as the range, as if using ranges::begin(r) as first and ranges::end(r) as last.

The function-like entities described on this page are niebloids, that is:

In practice, they may be implemented as function objects, or with special compiler extensions.

Contents

[edit] Parameters

first, last - the range of elements to reorder
r - the range of elements to reorder
nth - the iterator defining the partition point
comp - comparator used to compare the projected elements
proj - projection to apply to the elements

[edit] Return value

1) An iterator equal to last.
2) Same as (1) if r is an lvalue or of a borrowed_range type. Otherwise returns std::ranges::dangling.

[edit] Complexity

Linear in ranges::distance(first, last) on average.

[edit] Notes

The algorithm used is typically introselect although other selection algorithms with suitable average-case complexity are allowed.

[edit] Possible implementation

See also the implementation in msvc stl, libstdc++, and libc++: (1) / (2).

[edit] Example

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

Output:

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

[edit] See also

returns the largest element in a range
(niebloid)[edit]
returns the smallest element in a range
(niebloid)[edit]
divides a range of elements into two groups
(niebloid)[edit]
sorts the first N elements of a range
(niebloid)[edit]
partially sorts the given range making sure that it is partitioned by the given element
(function template) [edit]