string::npos 在这段代码中是什么意思?

新手上路,请多包涵

以下代码片段中的短语 std::string::npos 是什么意思?

 found = str.find(str2);

if (found != std::string::npos)
    std::cout << "first 'needle' found at: " << int(found) << std::endl;

原文由 boom 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 679
2 个回答

这意味着没有找到。

它通常是这样定义的:

 static const size_t npos = -1;

最好与 npos 而不是 -1 进行比较,因为代码更清晰。

原文由 Brian R. Bondy 发布,翻译遵循 CC BY-SA 3.0 许可协议

正如其他人所提到的, string::npos 它是 size_t 的最大值

这是它的定义:

 static constexpr auto npos{static_cast<size_type>(-1)};

困惑的是,错误的答案得到了投票。

这是一个快速测试示例:

 int main()
{
    string s = "C   :";
    size_t i = s.rfind('?');
    size_t b = size_t (-1);
    size_t c = (size_t) -1;
    cout<< i <<" == " << b << " == " << string::npos << " == " << c;

    return 0;
}

输出:

 18446744073709551615 == 18446744073709551615 == 18446744073709551615 == 18446744073709551615

...Program finished with exit code 0

原文由 Genci Ymeri 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题