迭代向量的元素时索引类型应该是什么?
我通常以这种方式迭代向量:
for (int i = 0; i < myVector.size(); i++) {
Element* e = myVector[i];
}
但是编译器通常会给我这个警告:
warning: C4018: '<' : signed/unsigned mismatch
所以如果 int
不正确,索引应该是哪种类型? vector::size() 似乎是“size_type”类型,但我宁愿使用更有意义的类型。有什么建议吗?
I usually iterate over a vector that way:
for (int i = 0; i < myVector.size(); i++) {
Element* e = myVector[i];
}
But then the compiler usually gives me this warning:
warning: C4018: '<' : signed/unsigned mismatch
So if an int
is not right, which type should the index be? vector::size() seems to be of a "size_type" type, but I'd rather use a more meaningful type. Any suggestion?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该使用
std::vector::size_type
1。其无符号整型。它通常与size_t
相同。要了解
size_type
和size_t
之间的区别,请参阅此主题:1.同样,您可以使用
std::string::size_type
、std::list::size_type
、std::deque:: size_type
、std::set::size_type
等。几乎所有标准容器都定义了一种名为size_type
的嵌套类型。有人可能会认为您应该使用迭代器而不是索引。但我也看到有时迭代器使 for 循环在水平方向上非常宽,请参见:
它看起来并不。事实上,有时它会让人恼火。在这种情况下,一些程序员更喜欢索引而不是迭代器。
在 C++0x 中,迭代器变得更加惯用。现在您可以使用迭代器,而不会使语法变得繁琐:
或者更好的是,使用基于范围的for循环:
You should use
std::vector<T>::size_type
1. Its unsigned integral type. Its usually same assize_t
.To know the difference between
size_type
andsize_t
, see this topic:1. Similarly, you can use
std::string::size_type
,std::list<T>::size_type
,std::deque<T>::size_type
,std::set<T>::size_type
, and so on. Almost all standard containers define a nested type calledsize_type
.One can argue that you should use iterator instead of index. But I also see that sometime iterator makes the for-loop very wide horizontally, see this :
It doesn't look. It in fact irritates sometimes. In such situations, some programmers prefers index over iterator.
In C++0x, iterator has been made more idiomatic. Now you can use iterator without making the syntax cumbersome:
Or even better, using range-based for loop:
编译器会发出警告,因为您的 int 已签名,但 size() 返回 size_t 类型的无符号 int。你不希望出现这种不匹配的情况,因为如果你的 int 为负数,它会引起头痛。您可以通过使用 size_t 来避免所有这些。
The compiler gives the warning because your int is signed but size() returns an unsigned int of type size_t. You don't want this kind of mismatch because it can cause headaches if your int is negative. You can avoid all of this by using size_t.
如果您只是使用它进行迭代,那么您可能需要使用:
这样做的优点是从
vector
更改为另一个容器时更加稳健。If you are just using it for iteration, then you might want to use:
This has the advantage of being slightly more robust to changing from
vector<>
to another container.只需使用
无符号
。使用size_t
你永远不会记得要包含的正确标头是什么,而使用vector::size_type
你最终会输入太多内容。出于所有实际目的,它们都是同一件事,只是重新定义了十几次。Just use
unsigned
. Withsize_t
you never remember what the right header to include is, and withvector<T>::size_type
you end up typing too much. For all practical purposes they are the same thing, just retypedef
ed a dozen of times.