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

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

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

还有这个:

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

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

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


当前回答

这两个代码段的工作原理相同。然而,unsigned int"路由是正确的。使用unsigned int类型将更好地用于使用它的实例中的vector。在vector对象上调用size()成员函数将返回一个无符号整数值,因此您希望将变量“i”与其自身类型的值进行比较。

此外,如果你仍然对“unsigned int”在代码中的表现感到不安,可以试试“uint”。这基本上是“unsigned int”的缩写版本,它的工作原理完全相同。您也不需要包含其他头文件来使用它。

其他回答

for (vector<int>::iterator it = polygon.begin(); it != polygon.end(); it++)
    sum += *it; 

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

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

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

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

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 );

c++ 11

我会使用像for_each这样的通用算法来避免搜索正确类型的迭代器和lambda表达式,以避免额外命名的函数/对象。

简短的“漂亮”的例子,你的特定情况(假设多边形是一个整数向量):

for_each(polygon.begin(), polygon.end(), [&sum](int i){ sum += i; });

测试地址:http://ideone.com/i6Ethd

别忘了包括:algorithm,当然还有vector:)

微软实际上也有一个很好的例子: 来源:http://msdn.microsoft.com/en-us/library/dd293608.aspx

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main() 
{
   // Create a vector object that contains 10 elements.
   vector<int> v;
   for (int i = 1; i < 10; ++i) {
      v.push_back(i);
   }

   // Count the number of even numbers in the vector by 
   // using the for_each function and a lambda.
   int evenCount = 0;
   for_each(v.begin(), v.end(), [&evenCount] (int n) {
      cout << n;
      if (n % 2 == 0) {
         cout << " is even " << endl;
         ++evenCount;
      } else {
         cout << " is odd " << endl;
      }
   });

   // Print the count of even numbers to the console.
   cout << "There are " << evenCount 
        << " even numbers in the vector." << endl;
}