我需要通过一个字符串向后循环。
// 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。什么是干净的解决方案?