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

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

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

还有这个:

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

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

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


当前回答

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

其他回答

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

我通常使用BOOST_FOREACH:

#include <boost/foreach.hpp>

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

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

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

关于向后迭代,请参阅这个答案。

Iterating forwards is almost identical. Just change the iterators / swap decrement by increment. You should prefer iterators. Some people tell you to use std::size_t as the index variable type. However, that is not portable. Always use the size_type typedef of the container (While you could get away with only a conversion in the forward iterating case, it could actually go wrong all the way in the backward iterating case when using std::size_t, in case std::size_t is wider than what is the typedef of size_type):


使用std::向量

使用迭代器

for(std::vector<T>::iterator it = v.begin(); it != v.end(); ++it) {
    /* std::cout << *it; ... */
}

重要的是,对于您不知道定义的迭代器,始终使用前缀增量形式。这将确保您的代码尽可能通用地运行。

使用Range c++ 11

for(auto const& value: a) {
     /* std::cout << value; ... */

使用索引

for(std::vector<int>::size_type i = 0; i != v.size(); i++) {
    /* std::cout << v[i]; ... */
}

使用数组

使用迭代器

for(element_type* it = a; it != (a + (sizeof a / sizeof *a)); it++) {
    /* std::cout << *it; ... */
}

使用Range c++ 11

for(auto const& value: a) {
     /* std::cout << value; ... */

使用索引

for(std::size_t i = 0; i != (sizeof a / sizeof *a); i++) {
    /* std::cout << a[i]; ... */
}

但是,请阅读向后迭代的答案,看看sizeof方法可以解决什么问题。

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