Caching the end iterator - Good idea or Bad Idea?

前端 未结 8 1742
臣服心动
臣服心动 2021-02-04 03:36

Generally speaking is it a good idea to cache an end iterator (specifically STL containers) for efficiency and speed purposes? such as in the following bit of code:



        
8条回答
  •  梦谈多话
    2021-02-04 04:09

    It really, really depends of what are you doing in the ... code.

    If the compiler can prove that vint.end() is not going to change then it might not matter, but you are at the mercy of the compiler optimizations then and how clear is the ... code.

    Your approach is the one that helps the compiler the most, you are promising that the end iterator will not be invalidated and that you are not going to modify the element in end (which is invalid any way). You cannot be more explicit than this about what you promise you will do in ....

    It is 2019, and for-range loops are basically equivalent to your code: https://en.cppreference.com/w/cpp/language/range-for

    {
        auto && __range = range_expression ;
        auto __begin = begin_expr ;
        auto __end = end_expr ;
        for ( ; __begin != __end; ++__begin) {
    
            range_declaration = *__begin;
            loop_statement
    
        }
    }
    

    which incidentally means that if you were not really interested in it, but in *it, you can put an end (no pun intended) to the dilemma and just write:

    std::vector vint;
    for(auto&& e : vint)
    {
       .... // use `e` instead of `*it`.
    }
    

提交回复
热议问题