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

For loop index type when checking for >=0 termination condition

本文关键字:条件 终止 类型 索引 循环 于检查 检查 gt      更新时间:2023-10-16

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

// 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,这是不直观的。什么是清洁的解决方案?

如果循环中不需要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();