在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.

我并不是说任何人都应该像我刚才那样编写代码。

我只是提供它作为另一种替代方案,它可以避免担心类型,将函数调用从循环中取出,并使循环计数器可用于更复杂场景中的调试信息等实际工作。

其他回答

在您示例中的特定情况下,我将使用STL算法来实现这一点。

#include <numeric> 

sum = std::accumulate( polygon.begin(), polygon.end(), 0 );

对于更一般,但仍然相当简单的情况,我认为:

#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>

using namespace boost::lambda;
std::for_each( polygon.begin(), polygon.end(), sum += _1 );

我通常使用BOOST_FOREACH:

#include <boost/foreach.hpp>

BOOST_FOREACH( vector_type::value_type& value, v ) {
    // do something with 'value'
}

它适用于STL容器、数组、c风格字符串等。

如果你的编译器支持它,你可以使用一个基于范围的for来访问vector元素:

vector<float> vertices{ 1.0, 2.0, 3.0 };

for(float vertex: vertices){
    std::cout << vertex << " ";
}

指纹:1 2 3。注意,您不能使用此技术来更改向量的元素。

第一个是类型正确,严格意义上的正确。(如果你想的是,size永远不可能小于零。)不过,这个警告在我看来是一个很好的被忽视的警告。

讲一点历史:

为了表示一个数字是否为负,计算机使用“符号”位。Int是一种有符号的数据类型,这意味着它可以保存正数和负数(大约- 20亿到20亿)。Unsigned只能存储正数(因为它不浪费元数据,所以可以存储更多:0到40亿)。

Std::vector::size()返回一个无符号值,因为向量的长度怎么可能是负的呢?

警告告诉您,不等式语句的右操作数可以比左操作数保存更多的数据。

从本质上讲,如果你有一个超过20亿项的向量,你使用一个整数来索引,你会遇到溢出问题(int将返回到- 20亿)。