Begin()和end()作为基于范围的for循环中的成员函数
begin() and end() as member functions in a range-based for loop
EDIT:这个问题中描述的问题是由不兼容的编译器引起的(详见注释)。
假设Generator是一个具有成员函数begin()
和end()
的类。我的理解是,根据c++ 11标准,在基于范围的循环中:
Generator g;
for (auto el: g) ;
Generator的成员函数begin()
和end()
将在循环中使用。
我编写了一个最小的代码来演示(如下)。但是,只有当我取消第一行的注释时,代码才能正常编译。也就是说,它只在
时起作用 #include<iostream>
。在相反的情况下,它产生错误:
‘begin’ was not declared in this scope (likewise for 'end').
我遇到了很多问题&与新标准中基于范围的循环相关的答案,但没有看到此错误的原因。
//#include<iostream>
class Iterator{
public:
Iterator (int i_) : i(i_)
{}
bool operator!=(const Iterator &other) const {
return i != other.i;
}
int operator*() const{
return i;
}
void operator++(){
++i;
}
private:
int i;
};
struct Generator{
Iterator begin()
{
return Iterator(0);
}
Iterator end(){
return Iterator(100);
}
};
int main(){
Generator g;
for (int i : g)
{
// do something.
}
}
更正: c++ 11 for-each循环使用给定for (auto i : c)
的以下逻辑:
-
如果类型是长度可推导的数组,则使用
c
和c + length
; -
如果类型是包含这些成员函数的类/结构,则使用
c.begin()
和c.end()
; -
使用
begin(c)
和end(c)
通过参数依赖查找如果上述失败
c++ 11 for-each循环使用std::begin
和std::end
,默认情况下转发到容器的begin
/end
函数。这样做是为了允许对数组进行专门化。这些定义需要在声明for循环时可见。
这些函数的定义没有隐式包含。这就是为什么没有#include
语句就会出现错误的原因。
它们在<iterator>
头文件中定义,在包含<iostream>
时包含。这就是当包含<iostream>
时程序编译的原因。
因此,编译器不执行标准的步骤1和2,而是依靠标准库begin/end来执行它们。
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么我的for循环不能正确获取argv
- 在基于范围的for循环中使用结构化绑定声明
- 通过for循环使用用户输入填充列表
- 使用for循环检查数组中的重复项
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 正在使用for循环创建QScatterSerie
- Python中的for循环与C++有何不同
- 在更改for循环的第三部分后,未使用for循环结果
- 在 for 循环中查找问题时遇到困难
- 嵌套for循环C++的问题(初学者)
- 如何用for循环在c++中生成单词三角形
- 如何在for循环中包含两个索引值的测试条件
- 带有多个独立参数的C++For循环
- 为什么我的程序在for循环中k=0时返回垃圾值
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- C++-For循环未执行
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- C++ 无法在字符数组中使用 for 循环打印字母模式