gpt4 book ai didi

c++ - 迭代单个左值

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:15:50 26 4
gpt4 key购买 nike

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

我的做法如下:

#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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com