对于检查 >=0 终止条件时的循环索引类型
For loop index type when checking for >=0 termination condition
我需要通过一个字符串向后循环。
// 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();
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 在没有太多条件句的情况下,我如何避免被零除
- 基于多个条件处理地图中的所有元素
- 条件constexpr函数
- 无论条件是否为true,if总是在c++中执行
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- C++ 即使不满足条件,循环也会终止
- 对于检查 >=0 终止条件时的循环索引类型
- 条件运算符不允许程序终止
- 即使仍然满足条件,该循环也会终止
- 有关清理此终止条件的建议
- 循环终止条件错误的 cpp 向量
- 循环中没有检查条件,但循环仍然终止C++
- 如何有条件地终止OpenMP中的并行区域
- cURL在条件下终止下载
- 满足条件后如何终止函数
- while 循环在满足条件时不会终止 (c++)
- 是否定义有一个随机的循环终止条件?