本文介绍了迭代在单个左值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想传递一个单值到一个函数,期望一对迭代器,并且它的行为,如果我传递一个迭代器到一个范围只包含这个值。

I'd like to pass a single lvalue to a function which expects a pair of iterators, and for it to act as if I'd passed a pair of iterators to a range containing just this value.

我的方法如下:

#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中正常工作,但我想知道如果这实际上是定义的行为,如果有任何潜在的问题?

This appears to work correctly in g++5.2, but I'm wondering if this is actually defined behaviour and if there are any potential issues?

推荐答案

首先我们从[expr.add] / 4

Yes this is defined behavior. First we have from [expr.add]/4

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

So a single object is treated as a array of length 1. Then we have [expr.add]/5

第一个数组元素也是最后一个数组元素,并且向最后一个数组元素添加1给你一个过去的对象,它是合法的。

So since the first array element is also the last array element, and adding 1 to the last array element gives you the one past the object, it is legal.

这篇关于迭代在单个左值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 16:45
查看更多