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
- [first, nth) is a valid range.
- [nth, last) is a valid range.
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:
Which are both true, the second interval is empty though. From the standard 25.3.2/1:
If the whole range was sorted the original
a.end()would be ata.end()and for the second part the range[nth, last)is empty so there are no elements for which to evaluate the!(*i > *j)andcomp(*j, *i) == falseconditions.