Welcome to OGeek Q&A 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...