C ++反向"for"循环 [英] C++ reverse 'for' loop
问题描述
我有一个向量:
std::vector<int> vec = {1, 2, 3};
我想做一个反向的for
循环.当我写的时候它有效:
And I want to make a reverse for
loop. It works, when I write:
for(int i = vec.size() - 1; i >= 0; --i) {
std::cout << i << std::endl; // 2, 1, 0
}
但是如果我写的话,我得到的数字非常大(如18446744073709223794)
But I get a very large number (like 18446744073709223794) if I write:
for(size_t i = vec.size() - 1; i >= 0; --i) {
std::cout << i << std::endl;
}
但是当我写这篇文章时,它们都可以工作:
But they both work when I write:
for(int i = 0; i < vec.size() - 1; ++i) {
std::cout << i << std::endl; // 1, 2, 3
}
// Or
for(size_t i = 0; i < vec.size() - 1; ++i) {
std::cout << i << std::endl; // 1, 2, 3
}
为什么使用size_t
时矢量的尺寸错误?
Why do I get the wrong size of the vector when I use size_t
?
我认为转换存在问题.
推荐答案
让编译器告诉您出什么问题了!
如果您在启用警告的情况下编译程序,则编译器会告诉您这样的话:
<source>: In function 'int main()':
7:43: warning: comparison of unsigned expression in '>= 0' is always true [-Wtype-limits]
7 | for(std::size_t i = vec.size() - 1; i >= 0; --i) {
| ~~^~~~
那是为什么?这是因为 std::size_t
是 unsigned 类型在C ++中;它仅代表非负数.阅读有关打开警告及其重要性的更多信息:为什么我应该始终启用编译器警告?
Why is that? It's because std::size_t
is an unsigned type in C++; it only represents non-negative numbers. Read more about turning on warnings and why it's important: Why should I always enable compiler warnings?
我已决定将此处的答案拆分为一个独立的问题,与OP的错误无关.请继续阅读.
I've decided to split my answer here off to a separate question, independent of OP's bug. Please go read it.
这篇关于C ++反向"for"循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!