我不明白为什么这个循环打印“无限”。如果字符串长度为1,length()-2如何生成一个大整数?
for(int i=0;i<s.length()-2;i++)
{
cout<<"INFINITE"<<endl;
}发布于 2016-06-14 11:03:43
std::string.length()返回一个size_t。这是一个无符号整数类型。您正经历整数溢出。伪码:
0 - 1 = int.maxvalue就你的情况而言,具体而言是:
(size_t)1 - 2 = SIZE_MAX 其中SIZE_MAX通常等于2^32 -1
发布于 2016-06-14 11:04:07
std::string::length()返回一个std::string::size_type。
std::string::size_type被指定为与allocator_traits<>::size_type (字符串的分配器)相同的类型。
此类型指定为无符号类型。
因此,数字将被包装(定义的行为)并变得巨大。到底有多大将取决于架构。
你可以用这个小程序在你的架构上测试它:
#include <limits>
#include <iostream>
#include <string>
#include <utility>
#include <iomanip>
int main() {
using size_type = std::string::size_type;
std::cout << "unsigned : " << std::boolalpha << std::is_unsigned<size_type>::value << std::endl;
std::cout << "size : " << std::numeric_limits<size_type>::digits << " bits" << std::endl;
std::cout << "npos : " << std::hex << std::string::npos << std::endl;
}就苹果x64而言:
unsigned : true
size : 64 bits
npos : ffffffffffffffffhttps://stackoverflow.com/questions/37810114
复制相似问题