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

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

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

还有这个:

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

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

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


当前回答

调用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等等)。

其他回答

使用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位体系结构变得越来越普遍的情况下。

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

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

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

添加这个,因为我在任何答案中都找不到它:对于基于索引的迭代,我们可以使用decltype(vec_name.size()),它将计算为std::vector<T>::size_type

例子

for(decltype(v.size()) i{ 0 }; i < v.size(); i++) {
    /* std::cout << v[i]; ... */
}

四年过去了,谷歌给了我这个答案。在标准c++ 11(又名c++ 0x)中,实际上有一种新的令人愉快的方式来做到这一点(以打破向后兼容性为代价):新的auto关键字。它为您省去了必须显式指定要使用的迭代器类型(再次重复vector类型)的痛苦,而(对编译器来说)显然应该使用哪种类型。v是你的向量,你可以这样做:

for ( auto i = v.begin(); i != v.end(); i++ ) {
    std::cout << *i << std::endl;
}

c++ 11甚至更进一步,提供了一种特殊的语法,用于迭代向量等集合。它消除了写千篇一律的东西的必要性:

for ( auto &i : v ) {
    std::cout << i << std::endl;
}

要在工作程序中查看它,构建一个auto.cpp文件:

#include <vector>
#include <iostream>

int main(void) {
    std::vector<int> v = std::vector<int>();
    v.push_back(17);
    v.push_back(12);
    v.push_back(23);
    v.push_back(42);
    for ( auto &i : v ) {
        std::cout << i << std::endl;
    }
    return 0;
}

在写这篇文章时,当你用g++编译它时,你通常需要通过给出一个额外的标志来设置它与新标准一起工作:

g++ -std=c++0x -o auto auto.cpp

现在你可以运行这个例子:

$ ./auto
17
12
23
42

请注意,关于编译和运行的说明是特定于Linux上的gnu c++编译器的,程序应该是平台(和编译器)独立的。