Speed accessing a std::vector by iterator vs by operator[]/index?

后端 未结 11 875
刺人心
刺人心 2020-12-03 04:42

Say, I have a

std::vector v;

in my code and I need to access its elements very often in the program, looping them forwa

11条回答
  •  鱼传尺愫
    2020-12-03 05:14

    I'd go for iterators, but what I would optimize is calling end() in the loop and would change preincrement to postincrement. I.e. I'd

    std::vector v;
    std::vector::iterator i,ie;
    std::vector::reverse_iterator j,je;
    
    // i loops forward, j loops backward
    for( i=v.begin(),ie=v.end(), j=v.rbegin(),je=v.rend(); i!=ie && j!=je; ++i,++j ){
        // some operations on v items
    }
    

    And I don't think it's premature microoptimization, it's just writing better code. Much less evil than calling every attempt to write efficient code premature microoptimization and substituting thinking with profiling.

提交回复
热议问题