range-for iterator类如何工作?

时间:2018-03-10 16:03:13

标签: c++ for-loop iterator

我知道,这段代码是如何工作的:

std::vector<int> sth;
for (auto const & elem : sth) { }

然而,这段代码对我来说很神秘:

namespace fs = std::filesystem;
for(auto & file : fs::directory_iterator("some/path"))
    std::cout << file << std::endl;

这个类(std::filesystem::directory_iterator)如何工作,它使我能够遍历整个容器?据我所知,范围是这样的:

// given "container"
for(auto it = std::begin(container); it != std::end(container); it++)
{
}

如果将directory_iterator作为container传递到这里,该怎么办?

1 个答案:

答案 0 :(得分:1)

基于范围的是传统for循环的语法糖

它只是在一个范围内执行for循环。

它比传统的for循环操作在一系列值上更具可读性,例如容器中的所有元素。

在幕后,编译器会将基于范围的for循环转换为如下所示:

{
    auto && __range = range_expression ; 
    for (auto __begin = begin_expr, __end = end_expr; __begin != __end; ++__begin) 
    { 
        range_declaration = *__begin; 
        loop_statement 
    } 
} 

begin_exprend_expr的定义如下:

  • 如果 range_expression 数组类型的表达式,那么begin_expr__range和{{1} }是end_expr,其中(__range + __bound)是数组中元素的数量(如果数组大小未知或类型不完整,则程序格式错误)

  • 如果 __bound 类类型 range_expression的表达式,其成员名为C和/或者名为begin的成员(无论此成员的类型或可访问性如何),则endbegin_expr__range.begin()end_expr

    < / LI>
  • 否则,__range.end();begin_exprbegin(__range)end_expr,这是通过参数依赖查找找到的(未执行非ADL查找)。

<强> end(__range)

std::filesystem::directory_iterator的情况下,它是上面的第三个选项,因为它具有begin and end个非成员函数,允许它在基于范围的for循环中使用。