在c++中迭代一个向量的正确方法是什么?

考虑这两个代码片段,这一个工作得很好:

for (unsigned i=0; i < polygon.size(); i++) {
    sum += polygon[i];
}

还有这个:

for (int i=0; i < polygon.size(); i++) {
    sum += polygon[i];
}

生成警告:有符号整数表达式和无符号整数表达式之间的比较。

对我来说,无符号变量看起来有点吓人,我知道无符号变量如果使用不当会很危险,所以-这是正确的吗?


当前回答

模糊但重要的细节:如果你像下面这样说“for(auto it)”,你得到的是对象的副本,而不是实际的元素:

struct Xs{int i} x;
x.i = 0;
vector <Xs> v;
v.push_back(x);
for(auto it : v)
    it.i = 1;         // doesn't change the element v[0]

要修改vector的元素,需要将迭代器定义为引用:

for(auto &it : v)

其他回答

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.

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

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

使用size_t:

for (size_t i=0; i < polygon.size(); i++)

引用维基百科:

stdlib.h和stddef.h头文件定义了一种名为size_t的数据类型,用于表示对象的大小。接受大小的标准库函数期望它们是size_t类型,而sizeof操作符的计算结果为size_t。 size_t的实际类型取决于平台;一个常见的错误是假定size_t与unsigned int相同,这可能导致编程错误,特别是在64位体系结构变得越来越普遍的情况下。

讲一点历史:

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

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

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

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

调用vector<T>::size()返回std::vector<T>::size_type类型的值,不是int, unsigned int或其他类型的值。

在c++中,容器的迭代通常是使用迭代器完成的,就像这样。

std::vector<T>::iterator i = polygon.begin();
std::vector<T>::iterator end = polygon.end();

for(; i != end; i++){
    sum += *i;
}

其中T是存储在向量中的数据类型。

或者使用不同的迭代算法(std::transform, std::copy, std::fill, std::for_each等等)。

在您示例中的特定情况下,我将使用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 );