我需要通过一个字符串向后循环。
// 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。什么是干净的解决方案?
答案 0 :(得分:2)
如果循环内不需要i
,则可以使用反向迭代器:
int main()
{
std::string s = "Hello, World!";
for (std::string::reverse_iterator i = s.rbegin(); i != s.rend(); ++i)
std::cout << *i;
}
答案 1 :(得分:0)
带有索引的首选循环看起来像
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();