std :: next with n> std :: distance(it,c.end()) [英] std::next with n > std::distance(it, c.end())
问题描述
我不想使用 std :: distance
,因为它将计算从我的迭代器到结束的整个距离。但我需要确保我有N或更多的元素从我的迭代器到结束。所以我使用下面的代码:
if(std :: next(it,n)!= c.end )// c is a std :: multimap
{
///我的逻辑
}
一切都很棒,使用我的编译器( g ++(GCC)4.8.3 20140911(Red Hat 4.8.3-9)
有疑问。在文档(cpprefenece.com&& cplusplus.com)中,我找不到任何有关 n> std :: distance(it,c.end())
或关于任何其他例外情况。所以。我的代码是否安全?或者我应该写我自己的 nextIfPossible
?
根据§24.4.4/ p3& p6迭代器操作[iterator.operations](强调Mine ):
code> template< class InputIterator,class Distance>
constexpr void advance(InputIterator& i,Distance n);
2 需要:n仅对双向和随机$ b为负$ b访问迭代器。
3 效果:增量(或负数n的减量)
迭代器参考i由n。template< class InputIterator>
constexpr InputIterator next(InputIterator x,
typename std :: iterator_traits< InputIterator> :: difference_type n = 1);
6 效果:相当于
advance(x,n); return x;
因此,没有绑定检查,因此可能会导致undefined如果输入 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
?
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())
.
这篇关于std :: next with n> std :: distance(it,c.end())的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!