C++ Vector at/[] operator speed

后端 未结 9 1535
借酒劲吻你
借酒劲吻你 2021-01-02 16:19

In order to give functions the option to modify the vector I can\'t do

curr = myvec.at( i );
doThis( curr );
doThat( curr );
doStuffWith( curr );
         


        
9条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-02 17:17

    Options that I see, in roughly inverse order of preference:

    1. Store pointers in your container instead of the actual objects. This may be advisable anyway, if the objects are complex enough that copying them around is problematic.
    2. Use the indexing operator [] instead of at().
    3. Just call at() once, and save it into a reference (see Kristo's answer above).
    4. Forget about it until you actually have a problem with excessive runtime. If that happens, profile your code first to make sure the bottleneck is here, and only then worry about doing one of the above to speed things up.

    Honestly, what you should do is play with the four different approaches, and just use the one that produces the easiest to understand code. In most cases we are happy to sacrifice a few machine cycles for code that is easier for human beings to maintain.

提交回复
热议问题