c++ - 循环判断条件为vec.size(),每次调用会不会优化?需要特地先求出size()吗?
怪我咯
怪我咯 2017-04-17 15:07:09
0
2
755

在遍历vector容器时,使用如下方法遍历:

for(int i=0; i<vec.size(); ++i)
    //do something

循环条件中使用了.size()操作,我用g++测试,每次编译器都会执行这个操作,那么效率会不会有影响?编译器不会优化吗?

需不需要提前求出来,比如:

const int size = vec.size();
for(int i=0; i<size; ++i)
    //do something
怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(2)
刘奇

Generally, please use iterator or range for to traverse the vector. If you must use index, you need to pay attention to whether the length of the vector will change during the loop.

std::vector<int> vi;

for (auto it = vi.begin(); it != vi.end(); ++it)
  // do something

for (auto & i : vi)
  // do something
阿神

If parameters such as optimization o2 are specified, it may be optimized. If you do not modify the size of the vector in the loop, in fact, because the size of the vector is stored in a variable, this process is not very expensive.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template