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

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

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745562792a4633207.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信