在遍历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
怪我咯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
阿神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.