c++ - 迭代单个左值

标签 c++ c++11 iterator

我想将单个左值传递给需要一对迭代器的函数,并且它的行为就像我将一对迭代器传递给仅包含该值的范围一样。

我的做法如下:

#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++ - 迭代单个左值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38441390/

相关文章:

c++ - QFile/QDataStream 写入现有数据

c++ - 构造一个内部有结构的类 C++

c++ - 是否可以强制 `std::make_shared` 使用类的新运算符?

java - 如何在没有 ConcurrentModificationException 的情况下在 Java 中保留两个迭代器并删除它们之间的键

c++ - boost make_shared 接受一个 const 引用。有什么办法可以解决这个问题?

c++ - 代码段错误

c++ - C++11 可以判断 std::thread 是否处于事件状态吗?

c++ - 如何将其切换为 unique_ptr?

c++ - 返回迭代器与松散耦合

java - 为什么Java迭代器构造函数签名没有迭代器类型?