std :: string :: npos的大小不同

Emi*_* A. 3 c++ string

我编写了一个程序,使用该find_last_of方法在字符串中查找字符.

// ...
unsigned found;
found = name.find_last_of(character);
if (found == std::string::npos) {
    std::cout << "NOT FOUND" << std::endl;
}
// ...
Run Code Online (Sandbox Code Playgroud)

我已经在两台机器上编译了代码,它只能在其中一台机器上运行(PC1).我调试了它,发现,对于PC1和PC2,std :: string :: npos是不同的.

如果没有找到任何字符,那么find_last_of == 4294967295两台机器返回的值.

PC1:

std::string::npos == 4294967295
Run Code Online (Sandbox Code Playgroud)

PC2:

std::string::npos == 18446744073709551615
Run Code Online (Sandbox Code Playgroud)

更多测试:

PC1:

sizeof(size_t) == 4
Run Code Online (Sandbox Code Playgroud)

PC2:

sizeof(size_t) == 8
Run Code Online (Sandbox Code Playgroud)

第一台机器使用32位操作系统,第二台机器使用64位操作系统.

我应该使用什么来比较find_last_of方法返回的值,使其在两台机器上都能正常工作?

Kar*_*ath 8

我应该使用什么来比较find_last_of方法返回的值,使其在两台机器上都能正常工作?

std::string::npos,position(found)的类型应该是size_t.

常量的具体大小可以在不同的体系结构上有所不同,但这不是您的担忧.

npos是一个静态成员常量值,对于size_t类型的元素具有最大可能值.