加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 迭代单个左值

发布时间:2020-12-16 03:40:03 所属栏目:百科 来源:网络整理
导读:我想将一个左值传递给一个需要一对迭代器的函数,并且它就像我将一对迭代器传递给只包含这个值的范围一样. 我的方法如下: #include iostream#include vectortemplatetypename Itervoid iterate_over(Iter begin,Iter end){ for(auto i = begin; i != end; ++
我想将一个左值传递给一个需要一对迭代器的函数,并且它就像我将一对迭代器传递给只包含这个值的范围一样.

我的方法如下:

#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会为您提供一个超过该对象的元素,这是合法的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读