最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c++ - What if the nth iterator is not within the range [first, last) when use std::nth_element - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked Nov 19, 2024 at 12:11 PkDrewPkDrew 1,0702 gold badges7 silver badges23 bronze badges 1
  • Not official as the standard, but cppreference is good enough std::nth_element, and it covers your case. – Jarod42 Commented Nov 19, 2024 at 13:35
Add a comment  | 

1 Answer 1

Reset to default 4

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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论