I read the description of std::nth_element at http://www.sgi.com/tech/stl/nth_element.html
template <class RandomAccessIterator>
void nth_element(RandomAccessIterator first, RandomAccessIterator nth,
RandomAccessIterator last);
Note that the preconditions are
My question is:
Is it valid to call std::nth_element(a.begin(), a.end(), a.end())? If so, what's its effect? It doesn't violate the preconditions above, anyway. Anywhere in the language standard (or other documents) stated that nth must be pointing to an element in a?
It's valid and is probably, but not guaranteed by the standard, a null operation. With the given data, the two preconditions become:
[a.begin(), a.end()) is a valid range.
[a.end(), a.end()) is a valid range.
Which are both true, the second interval is empty though. From the standard 25.3.2/1:
After nth_element the element in the position pointed to by nth is the element that would be in that position if the whole range were sorted. Also for any iterator i in the range [first, nth) and any iterator j in the range [nth, last) it holds that: !(*i > *j) or comp(*j, *i) == false.
If the whole range was sorted the original a.end() would be at a.end() and for the second part the range [nth, last) is empty so there are no elements for which to evaluate the !(*i > *j) and comp(*j, *i) == false conditions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With