Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::next with n > std::distance(it, c.end())

Tags:

c++

c++11

stl

I do not want to use std::distance because it will calculate whole distance from my iterator to the end. But I need to be sure that I have N or more elements from my iterator to the end. So I'm using next code:

if (std::next(it, n) != c.end()) // c is a std::multimap
{
    /// my logic
}

Everything is great and working with my compiler (g++ (GCC) 4.8.3 20140911 (Red Hat 4.8.3-9)) but I have doubts. In documentation (cpprefenece.com && cplusplus.com) I can not find any information about case when n > std::distance(it , c.end()) or about any other exceptional cases. So. Is my code safe? Or I should write my own nextIfPossible?

like image 639
denys Avatar asked Nov 03 '25 21:11

denys


1 Answers

next(it, n) is undefined behavior if distance(it, c.end()) is less than n.

[C++14: 5.7/5] If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

See here for more info: Are non dereferenced iterators past the "one past-the-end" iterator of an array undefined behavior?

You must write a nextIfPossible or your code is undefined. That said, since I'm guessing this is a Random Access Iterator, you'll find working with indexes to benchmark faster than working with iterators in the case where bounds checking must be performed: https://stackoverflow.com/a/37299761/2642059

So I'd recommend not even bothering with iterators or nextIfPossible but just using an index and checking it against the size.

like image 84
Jonathan Mee Avatar answered Nov 06 '25 12:11

Jonathan Mee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!