c – 迭代单个左值

我想将一个左值传递给一个需要一对迭代器的函数,并且它就像我将一对迭代器传递给只包含这个值的范围一样.

我的方法如下:

#include <iostream>
#include <vector>

template<typename Iter>
void iterate_over(Iter begin,Iter end){
    for(auto i = begin; i != end; ++i){
        std::cout << *i << std::endl;
    }
}

int main(){
    std::vector<int> a{1,2,3,4};
    iterate_over(a.cbegin(),a.cend());

    int b = 5;
    iterate_over(&b,std::next(&b));
}

这似乎在g 5.2中正常工作,但我想知道这是否是实际定义的行为以及是否存在任何潜在问题?

解决方法

是的,这是定义的行为.首先我们来自[expr.add] / 4

For the purposes of these operators,a pointer to a nonarray object behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.

因此,单个对象被视为长度为1的数组.然后我们有[expr.add] / 5

[…]Moreover,if the expression P points to the last element of an array object,the expression (P)+1 points one past the last element of the array object, and if the expression Q points one past the last element of an array object,the expression (Q)-1 points to the last element of the array object. 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.

强调我的

因此,由于第一个数组元素也是最后一个数组元素,并且向最后一个数组元素添加1会为您提供一个超过该对象的元素,这是合法的.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...