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

后端 未结 6 705
梦毁少年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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-19 01:46

    Don't decide whether to go for one or the other by thinking in terms of performance; your compiler may or may not inline the call - and std::vector::size() has constant complexity, too.

    What you should really consider is correctness, because the two versions will behave very differently if you add or remove elements while iterating.

    If you don't modify the vector in any way in the loop, stick with the former version to avoid a little bit of state (the n variable).

提交回复
热议问题