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

标签 c++ range-based-loop

我正在尝试将 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/

相关文章:

c++ - 构建 ASP.NET Core 和 C++ 二进制文件的 Dockerfile

C++ 循环遍历 map

c++ - 遍历无序 multimap

c++ - std::filesystem::directory_iterator 真的是迭代器吗?

c++ - 为什么我可以在 C++ 中使用 for 循环将右值绑定(bind)到非常量引用?

c++ - 如何将大括号括起来的初始化列表传递给函数?

C++ vector 打印出奇怪的元素

c++ - 如何将可变数量的值读入 std::tuple?

c++ - 将 protected 析构函数虚拟化是否有用?

c++ - 如何使用 dup2 定期读取重定向到文件描述符的 stdout 上的内容