检查> = 0终止条件时为循环索引类型

我需要通过一个字符串向后循环。

// std::string str assumed to be defined at this point
for (std::size_t i = str.length() - 1; i >= 0; i--) {
  // perform some check on str[i]
}

问题描述
现在,如果我使用int i循环索引,则此方法有效,因为我最终将变为-1,并且循环终止。当对运行中的索引使用std::size_t i(无符号)时,当它变为“低于”零时,它将变得非常大,因此循环不会终止,最终会导致分段错误。鉴于我要使用std :: size_t作为循环索引类型,因此解决此问题的首选方法是什么,因为std :: string :: length返回std :: size_t,而不是int。

可能的解决方案

for (std::size_t i = str.length(); i > 0; i--) {
  // perform some check on str[i - 1]
}

我认为这真的很丑,因为我们将i用作不直观的“偏移” idx。什么是干净的解决方案?

wan_XM 回答:检查> = 0终止条件时为循环索引类型

如果循环内不需要i,则可以使用反向迭代器:

int main()
{
    std::string s = "Hello,World!";
    for (std::string::reverse_iterator i = s.rbegin(); i != s.rend(); ++i)
        std::cout << *i;
}
,

带有索引的首选循环看起来像

for ( std::size_t i = str.length(); i != 0; i--) {
  // perform some check on str[i-1]
  //                       ^^^^^^^^
}

for ( std::size_t i = str.length(); i-- != 0; ) {
  // perform some check on str[i]
  //                       ^^^^^^
}

也代替声明

std::size_t i = str.length();

您可能只是写

auto i = str.length();
本文链接:https://www.f2er.com/3137900.html

大家都在问