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

时间:2014-01-17 10:18:49

标签: c++ string

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

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

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

如果未找到任何字符,则find_last_of == 4294967295为两台计算机返回的值。

PC1:

std::string::npos == 4294967295

PC2:

std::string::npos == 18446744073709551615

更多测试:

PC1:

sizeof(size_t) == 4

PC2:

sizeof(size_t) == 8

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

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

2 个答案:

答案 0 :(得分:8)

  

我应该使用什么来比较find_last_of返回的值   使它适用于两台机器的方法?

std::string::npos,位置类型(found)应为size_t

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

  

npos是最大可能的静态成员常量值   size_t类型的元素的值。

答案 1 :(得分:4)

只需查看功能 - http://en.cppreference.com/w/cpp/string/basic_string/find_last_of

  

size_type find_last_of(const basic_string&amp; str,size_type pos = 0)const; (1)
  size_type find_last_of(const CharT * s,size_type pos,size_type count)const; (2)
  size_type find_last_of(const CharT * s,size_type pos = 0)const; (3)
  size_type find_last_of(CharT ch,size_type pos = 0)const; (4)

显然,std::string::size_type是存储返回值的正确类型,之后与std::string::npos的比较将起作用。

相关问题