实现昂贵的c++迭代器
Implementing expensive c++ iterator
假设我们有这样一个类:
#include <cstdio>
struct A{
struct it{
it(int i) : i(i){
printf("c-tor %dn", 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("forn");
for(A::it i = a.begin(); i != a.end(); ++i)
printf("%dn", *i);
printf("c++11 forn");
for(int j : a)
printf("%dn", j);
printf("memoizen");
A::it my_end = a.end();
for(A::it i = a.begin(); i != my_end; ++i)
printf("%dn", *i);
printf("refn");
for(A::it i = a.begin(); i != a.xend(); ++i)
printf("%dn", *i);
}
编辑:该迭代器为const迭代器。在这个例子中是非常简单的,这是不明显的。
当第一次执行for循环时,为每次循环迭代构造新的end迭代器。
如果将类从end()赋值给一个变量(例如memoize),就不会出现这样的问题。
c++ 11可能做了完全相同的事情。
最后,end()
可能返回reference,但代码要复杂得多,将来可能会出现问题。
参见Herb Sutter关于临时对象的GotW。他建议在进入循环之前只调用一次end()
,避免每次迭代都调用end()
。
然而,他建议度量迭代器临时创建是否是性能瓶颈(例如,它可能非常快,甚至被编译器优化),以避免过早优化。
定义 : 不成熟的优化是指在没有实际需要的数据的情况下,以效率的名义使代码变得更复杂。
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++中带有List类的迭代器Segfault
- 如何在c++迭代器类型中包装std::chrono
- 集合上的输出迭代器:assign和increment迭代器
- Boost Spirit,获取迭代器内部语义动作
- 对于set上的循环-获取next元素迭代器
- 为什么output_editor Concept不需要output_e迭代器标记
- c++17文件系统::recursive_directory迭代器()在mac上没有给出这样的目录,但在windows上
- 使用迭代器时如何访问对象在向量中的位置?
- std::vector::迭代器是否可以合法地作为指针
- 跟随整数索引列表的自定义类迭代器
- 不明白迭代器,引用和指针失效,一个例子
- 我可以使用反向迭代器作为ForwardIt吗
- ESP8266单片机矢量迭代器的C++问题
- 如何在C++中将迭代器作为函数参数传递
- 是否应避免从非常量迭代器转换为常量迭代器?
- 如何在 c++ 中将字符串迭代器变量传递给函数?
- 为什么 vector 的随机访问迭代器给出与指针不同的内存地址?
- 为什么 C++ std::unordered_map 从 emplace/ 找到返回一个迭代器?