Is it expensive to compute vector size in for loops, each iteration?

后端 未结 6 802
梦毁少年i
梦毁少年i 2021-02-19 01:20

Does the c++ compiler take care of cases like, buildings is vector:

for (int i = 0; i < buildings.size(); i++) {}

that is, does it notice if

6条回答
  •  遇见更好的自我
    2021-02-19 02:10

    I write loops like this:

    for (int i = 0, maxI = buildings.size(); i < maxI; ++i)
    

    Takes care of many issues at once: suggest max is fixed up front, no more thinking about lost performance, consolidate types. If evaluation is in the middle expression it suggests the loop changes the collection size.

    Too bad language does not allow sensible use of const, else it would be const maxI.

    OTOH for more and more cases I rather use some algo, lambda even allows to make it look almost like traditional code.

提交回复
热议问题