下面的代码按预期工作,即它反向打印字符串
std::string s("abcd");
for (int i=s.length()-1; i>=0; --i) {
std::cout << s[i];
}
然而,下面的代码进入无限循环打印垃圾字符,最后崩溃-
std::string s("abcd");
for (std::size_t i=s.length()-1; i>=0; --i) {
std::cout << s[i];
}
为什么使用 size_t
作为 i
的类型会使程序崩溃?
我在 Windows 上使用 MinGW 附带的 g++
C:/MinGW/bin/g++ --version
g++ (GCC) 6.1.0
最佳答案
这是因为 std::size_t
不能存储负数,因此条件总是为真
关于C++ 字符串 size_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38289521/