c++ - 实现昂贵的 C++ 迭代器

标签 c++ c++11 iterator

假设我们有这样的类(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/

相关文章:

rust - 如何为Tree <T>实现IntoIterator?

java - 我怎样才能在java中进行这个 map 迭代?

c++ - streambuf、ostream、ostreambuf、istream、istreambuf 和关联的迭代器

c++ - operator=(double) 隐藏在派生类中

c++ - QThread:线程仍在运行时被销毁,QMutex 被销毁

c++ - 如何从派生构造函数初始化列表初始化模板基类的成员?

c++ - 可变参数模板参数的元迭代

c++ - Google Benchmark,如何只调用一次代码?

c++ - 如何使用虚函数返回指向基类的指针?

c++ - 为什么在调用不明确的ctor时没有编译时错误?