在c++中迭代一个向量的正确方法是什么?
考虑这两个代码片段,这一个工作得很好:
for (unsigned i=0; i < polygon.size(); i++) {
sum += polygon[i];
}
还有这个:
for (int i=0; i < polygon.size(); i++) {
sum += polygon[i];
}
生成警告:有符号整数表达式和无符号整数表达式之间的比较。
对我来说,无符号变量看起来有点吓人,我知道无符号变量如果使用不当会很危险,所以-这是正确的吗?
auto polygonsize = polygon.size(), i=polygonsize;
for (i=0; i < polygonsize; i++) {
sum += polygon[i];
}
This
uses auto to avoid us worrying about types.
It takes any function calls e.g. the size() function call out of the loop to avoid unnecessary repeated function calls.
It makes the loop counter available. Purists will want to work with the n'th element with no knowledge of the value of n, and see this as bad.
It appears to have an unecessary statement i=polygonsize initializing the loop variable when it's declared, but this should disappear if there is a half decent code optimizer, and is merely to ensure i has the correct type.
我并不是说任何人都应该像我刚才那样编写代码。
我只是提供它作为另一种替代方案,它可以避免担心类型,将函数调用从循环中取出,并使循环计数器可用于更复杂场景中的调试信息等实际工作。