在计算中使用指向可索引集合之外的迭代器是否安全?(Is it safe to use iterator pointing beyond indexable collection in calculat

编程入门 行业动态 更新时间:2024-10-21 16:04:43
在计算中使用指向可索引集合之外的迭代器是否安全?(Is it safe to use iterator pointing beyond indexable collection in calculations?)

当我有简单的指针时,我可以像这样安全地包装数组:

p+=X; // p pointer p can point beyond end of array if(p>=array+array_size) p-=array_size; // forget about potential multiple wrap

我可以安全地为任何可索引容器的迭代器做同样的事情,尤其是 双端队列?:

p+=x; if(p>=mydeque.end()) p-=mydeque.size(); // forget about potential multiple wrap

换句话说:计算迭代器指向集合之外是否安全?

When I have simple pointer I can safely wrap array like this:

p+=X; // p pointer p can point beyond end of array if(p>=array+array_size) p-=array_size; // forget about potential multiple wrap

can I do the same safely for iterator over any indexable container, esp. deque?:

p+=x; if(p>=mydeque.end()) p-=mydeque.size(); // forget about potential multiple wrap

In other words: is it safe to take into calculations iterator pointing beyond collection?

最满意答案

你只能做p += X; 只要它仍然指向数组/容器内或数组/容器的末尾(第5.7节):

如果指针操作数和结果都指向同一个数组对象的元素,或者指向数组对象的最后一个元素,则评估不应产生溢出; 否则,行为未定义。

指针之间的比较也是如此。 它们必须指向相同的数组或指向结束的数组。 他们不能指出更多。

You can only do p += X; as long as it still points within the array/container or one past the end of the array/container (§5.7):

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.

The same is true for comparisons between pointers. They must both be pointing at the same array or one past the end. They cannot be pointing further than that.

更多推荐

本文发布于:2023-07-31 02:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340490.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:索引   迭代   safe   iterator   calculations

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!