迭代std :: vector:无符号vs有符号索引变量 [英] Iteration over std::vector: unsigned vs signed index variable

查看:168
本文介绍了迭代std :: vector:无符号vs有符号索引变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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?

推荐答案

向后倒转



查看。这个回答是什么?

Iterating Backwards

See this answer.

这几乎完全相同。只需更改迭代器/交换递减递增。你应该喜欢迭代器。有些人告诉你使用 std :: size_t 作为索引变量类型。但是,这不是便携式的。总是使用容器的 size_type typedef(虽然你可以在正向迭代的情况下只转换一个转换,但在反向迭代的情况下它可能会出错当使用 std :: size_t 时,如果 std :: size_t 比<$ c的typedef $ c> size_type ):

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



使用索引



Using indices

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



使用数组



使用迭代器



Using arrays

Using iterators

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



使用范围C ++ 11



Using Range C++11

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



使用索引



Using indices

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

读取反向迭代的答案, c $ c> sizeof 方法可以产生。

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

这篇关于迭代std :: vector:无符号vs有符号索引变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆