简体   繁体   English

For-Loop 带有负迭代器的“空”向量?

[英]For-Loop a "Empty" Vector with negative iterator?

Im trying to loop through the newest 10 Entries of a vector.我试图遍历向量的最新 10 个条目。 The Size of the Vector can be anything between 0 and 100.向量的大小可以是 0 到 100 之间的任何值。

As easiest solution, i though starting the loop at vector.size() - 10;作为最简单的解决方案,我虽然在 vector.size() - 10 处开始循环; and then check inside if its not negative, i can access the vector object.然后检查内部是否为负,我可以访问向量对象。

Sadly, it does not work (doesnt loop at all), but if i replace the same Code with hardcoded numbers, it works.可悲的是,它不起作用(根本不循环),但是如果我用硬编码数字替换相同的代码,它就起作用了。

What im doing wrong, or where is the problem here?我做错了什么,或者问题出在哪里?

for (int i = -10; i < 0; i++) {
    std::cout << "Normal Loop: i = " << i << std::endl;
}

This works, but looping over a vector doesnt:这有效,但循环向量不:

std::vector<int> myVector;
for (int i = myVector.size() - 10; i < myVector.size(); i++) {
    std::cout << "Vector Loop: i = " << i << std::endl;
}

The first loop prints all 10 Numbers (From -10 to -1), but the second Loop doesnt print anything.第一个循环打印所有 10 个数字(从 -10 到 -1),但第二个循环不打印任何内容。

Since myVector.size() is 0 right now, it should be the same output as the first one由于 myVector.size() 现在为 0,它应该与第一个输出相同

That's because std::vector::size() returns size_type as type, this type is unsigned.那是因为std::vector::size()size_type作为类型返回,该类型是无符号的。 This means that i < myVector.size() compares two different types, int and unsigned int .这意味着i < myVector.size()比较两种不同的类型, intunsigned int The compiler will "promote" your int to an unsigned type.编译器会将您的 int “提升”为无符号类型。 Because this int is negative and unsigned types can't hold negative values it will wrap around and you'll end up with a very big value and thus the loop condition is never met.因为这个 int 是负数并且无符号类型不能保存负值,所以它会环绕,你最终会得到一个非常大的值,因此永远不会满足循环条件。

You could cast size() explicitly:您可以显式转换size()

std::vector<int> myVector;
for (int i = myVector.size() - 10; i < static_cast<int>(myVector.size()); i++) {
    std::cout << "Vector Loop: i = " << i << std::endl;
}

Or for a cleaner approach try using rbegin() and loop until rend() or until you've looped 10 times, something like:或者为了更rbegin()方法,尝试使用rbegin()并循环直到rend()或直到循环 10 次,例如:

std::vector<int> myVector;
//fill vector..
auto itr = myVector.rbegin();
int count = 10;
while(itr != myVector.rend() && count-- > 0)
{
  //process.
  ++itr;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM