gpt4 book ai didi

c++ - C++ 中基于范围的 for 循环的范围表达式

转载 作者:行者123 更新时间:2023-12-01 22:52:21 25 4
gpt4 key购买 nike

我正在尝试将 vector 指针传递给基于范围的 for 循环以用于其范围表达式。

下面是基于范围的 for 循环的语法:

attr(optional) for ( init-statement(optional) range-declaration : range-expression )
loop-statement

引用自cppreference.com:

range-expression is evaluated to determine the sequence or range to iterate. Each element of the sequence, in turn, is dereferenced and is used to initialize the variable with the type and name given in range-declaration.

begin-expr and end-expr are defined as follows:

If range-expression is an expression of array type, then begin-expr is __range and end-expr is (__range + __bound), where __bound is the number of elements in the array (if the array has unknown size or is of an incomplete type, the program is ill-formed)
If range-expression is an expression of a class type C that has both a member named begin and a member named end (regardless of the type or accessibility of such member), then begin-expr is __range.begin() and end-expr is __range.end();
Otherwise, begin-expr is begin(__range) and end-expr is end(__range), which are found via argument-dependent lookup (non-ADL lookup is not performed).

我定义了 begin 和 end 并希望它们用于 begin-expr,以取消引用指针,但失败了。这是我的代码:

#include <iostream>                // std::cout
#include <vector>
using namespace std;

vector<int>::iterator
begin(vector<int> *a)
{
return a->begin();
}

vector<int>::iterator
end(vector<int> *a)
{
return a->end();
}

int main()
{
vector<int> v = {1,2,3,4};
vector<int> *p = &v;
for (auto i : p) {
cout << i << endl;
}
return 0;
}

我仍然遇到以下编译错误:

Invalid range expression of type 'vector<int> *'; did you mean to dereference it with '*'?

我在这里遗漏了什么吗?

最佳答案

Otherwise, begin-expr is begin(__range) and end-expr is end(__range), which are found via argument-dependent lookup (non-ADL lookup is not performed).

begin()end()只能通过 ADL 查找。对于指针,it works like this :

For arguments of type pointer to T or pointer to an array of T, the type T is examined and its associated set of classes and namespaces is added to the set.

std::vector<int> 关联的唯一命名空间|是namespace std ,所以这就是begin()end()将被查找。

begin()end()进入namespace std使代码工作,但将新声明添加到 std导致未定义的行为(有一些异常(exception)),不应该这样做。

关于c++ - C++ 中基于范围的 for 循环的范围表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74092366/

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