Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

According to the standard §24.4.4/p3 & p6 Iterator operations [iterator.operations] (Emphasis Mine):

template <class InputIterator, class Distance>
constexpr void advance(InputIterator& i, Distance n);

2 Requires: n shall be negative only for bidirectional and random access iterators.

3 Effects: Increments (or decrements for negative n) iterator reference i by n.

template <class InputIterator>
constexpr InputIterator next(InputIterator x,
typename std::iterator_traits<InputIterator>::difference_type n = 1);

6 Effects: Equivalent to: advance(x, n); return x;

Consequently, there's no bound checking and therefore you may result in undefined behaviour if input n is greater than std::distance(it , c.end()).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...