实现昂贵的c++迭代器

Implementing expensive c++ iterator

本文关键字:c++ 迭代器 实现      更新时间:2023-10-16

假设我们有这样一个类:

#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()

然而,他建议度量迭代器临时创建是否是性能瓶颈(例如,它可能非常快,甚至被编译器优化),以避免过早优化

定义 : 不成熟的优化是指在没有实际需要的数据的情况下,以效率的名义使代码变得更复杂。