Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading