I've almost understood many STL algorithms until I've reached the algorithm std::nth_element
. I 'm stuck on it; I don't know how it works and it does do exactly.
For education and understanding sake can someone explain to me how the algorithm std::nth_element
works?
std::vector<int> v{ 9, 3, 6, 2, 1, 7, 8, 5, 4, 0 };
std::nth_element(v.begin(), v.begin() + 2, v.end());
for (auto i : v)
std::cout << i << " ";
std::cout << '\n';
The output:
1 0 2 3 6 7 8 5 4 9
- So where is
nth
element here? - How and what the algorithm does?
- Does it do some sort of partial sorting?
Here is some explanation from cppreference.com:
nth_element
is a partial sorting algorithm that rearranges elements in [first, last) such that:
- The element pointed at by nth is changed to whatever element would occur in that position if [first, last) was sorted.
- All of the elements before this new nth element are less than or equal to the elements after the new nth element. More formally, nth_element partially sorts the range [first, last) in ascending order so that the condition
!(*j < *i)
(for the first version, orcomp(*j, *i) == false
for the second version) is met for any i in the range [first, nth) and for any j in the range [nth, last). The element placed in the nth position is exactly the element that would occur in this position if the range was fully sorted.nth may be the end iterator, in this case the function has no effect.
- I am still confused about it. What is nth element and how to implement a possible algorithm like that?. For education sake I've mimicked many STL algorithms. Thank you so much!