Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What the effect of std::nth_element(a.begin(), a.end(), a.end())?

Tags:

c++

stl

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

  1. [first, nth) is a valid range.
  2. [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?

like image 437
updogliu Avatar asked Jun 28 '12 13:06

updogliu


1 Answers

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.

like image 54
Andreas Brinck Avatar answered Oct 02 '22 19:10

Andreas Brinck