tex*_*uce 8 c++ iterator c++11
我有一个这样的课:
class Foo {
private:
int a,b,c,d;
char bar;
double m,n
public:
//constructors here
};
Run Code Online (Sandbox Code Playgroud)
我想在课堂上允许使用范围循环,例如
Foo foo {/*...*/};
for(auto& f : foo) {
//f will be a specific order such as c,b,d,(int)m,(int)bar,a,(int)n
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?我在看迭代器,但不知道range-for循环的要求是什么.(请不要让我使用数组或STL类型)
Mik*_*our 10
循环定义为等效于:
for ( auto __begin = <begin-expr>,
__end = <end-expr>;
__begin != __end;
++__begin ) {
auto& f = *__begin;
// loop body
}
Run Code Online (Sandbox Code Playgroud)
其中<begin-expr>
是foo.begin()
,或begin(foo)
如果不存在一个合适的成员函数,并且同样为<end-expr>
.(这是C++ 11 6.5.4中规范的简化,对于这种特殊情况,范围是类类型的左值).
所以你需要定义一个支持预增量++it
,取消引用*it
和比较的迭代器类型i1 != i2
; 或者
foo
公众成员函数begin()
和end()
; 要么begin(foo)
并end(foo)
在相同的命名空间中,foo
以便可以通过参数依赖查找找到它们.