假设我们有这样的类(class):
#include <cstdio>
struct A{
struct it{
it(int i) : i(i){
printf("c-tor %d\n", i);
}
it &operator++(){
i++;
return *this;
}
int operator*(){
return i;
}
bool operator!=(const it &ot){
return i != ot.i;
}
int i;
};
it begin() const{
return it(0);
}
it end() const{
return it(10);
}
it end_it = it(10);
const it &xend() const{
return end_it;
}
};
int main(){
A a;
printf("for\n");
for(A::it i = a.begin(); i != a.end(); ++i)
printf("%d\n", *i);
printf("c++11 for\n");
for(int j : a)
printf("%d\n", j);
printf("memoize\n");
A::it my_end = a.end();
for(A::it i = a.begin(); i != my_end; ++i)
printf("%d\n", *i);
printf("ref\n");
for(A::it i = a.begin(); i != a.xend(); ++i)
printf("%d\n", *i);
}
编辑:迭代器是常量迭代器。在示例中非常简单,这一点并不明显。
当我们第一次执行 for 循环时,会为每个循环迭代构造新的结束迭代器。
如果我们将 end() 中的类分配给变量(例如 memoize),则不存在这样的问题。
C++11 可能会做完全相同的事情。
最后,end()
可能会返回引用,但代码要复杂得多,将来可能会出现问题。
实现昂贵的迭代器的正确方法是什么?
最佳答案
请参阅 Herb Sutter 的 GotW,网址为 temporary objects 。他建议您在进入循环之前只能调用 end()
一次,从而避免每次迭代都调用 end()
。
但是,他建议衡量迭代器临时创建是否是性能瓶颈(例如,它可能非常快,甚至被编译器优化),以避免过早优化。
Definition: Premature optimization is when you make code more complex in the name of efficiency without data that it’s actually needed.
关于c++ - 实现昂贵的 C++ 迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33164470/