迭代 std::vector:无符号与有符号索引变量

2022-01-07 00:00:00 unsigned signed c++ stl

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

What is the correct way of iterating over a vector in C++?

考虑这两个代码片段,这个可以正常工作:

Consider these two code fragments, this one works fine:

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

还有这个:

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

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

我是 C++ 世界的新手,所以 unsigned 变量对我来说看起来有点吓人,我知道 unsigned 变量如果使用不当会很危险,所以 - 这是正确的吗?

I'm new in the world of C++, so the unsigned variable looks a bit frightening to me and I know unsigned variables can be dangerous if not used correctly, so - is this correct?

推荐答案

要向后迭代,请参阅 这个答案.

For iterating backwards see this answer.

向前迭代几乎相同.只需按增量更改迭代器/交换递减.你应该更喜欢迭代器.有些人告诉您使用 std::size_t 作为索引变量类型.但是,这不是便携式的.始终使用容器的 size_type typedef(虽然在向前迭代的情况下你可以只进行一次转换,但在使用 std 时在向后迭代的情况下它实际上可能一直出错::size_t,以防 std::size_tsize_type 的 typedef 更宽):

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

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

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

Important is, always use the prefix increment form for iterators whose definitions you don't know. That will ensure your code runs as generic as possible.

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; ... */
}

使用范围 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 方法可以解决什么问题.

Read in the backward iterating answer what problem the sizeof approach can yield to, though.

相关文章