Home  >  Q&A  >  body text

c++ - 循环判断条件为vec.size(),每次调用会不会优化?需要特地先求出size()吗?

在遍历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
怪我咯怪我咯2765 days ago714

reply all(2)I'll reply

  • 怪我咯

    怪我咯2017-04-17 15:09:09

    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

    reply
    0
  • 阿神

    阿神2017-04-17 15:09:09

    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.

    reply
    0
  • Cancelreply