c++algorithmvector

What if the nth iterator is not within the range [first, last) when use std::nth_element


I cannot find any official definition related to handling of std::nth_element(first, nth, last) if nth is outside range [first, last).

As an attempt to figure it out, I did a toy test on my machine:

std::vector<int> arr{ 7, 3, 9, 6, 4 };
std::nth_element( arr.begin() + 1, arr.begin(), arr.end() );
for (int num : arr) {
    printf("%d", num);
}

MSVC gives me assertion fail in stl src code of vector, saying "vector iterator range transposed". Is it an undefined behavior?


Solution

  • Yes, it is undefined behaviour if

    [first, nth) or [nth, last) is not a valid range.

    Which says as much as that nth needs to lie between first and last.