【问题标题】:Which is better to check if a character exists in a std::string? find or find_first_of?哪个更好地检查 std::string 中是否存在字符? find 还是 find_first_of?
【发布时间】:2019-05-12 10:37:05
【问题描述】:

std::string 有两个不同的成员函数做同样的事情:

size_type find( CharT ch, size_type pos = 0 ) const noexcept;
size_type find_first_of( CharT ch, size_type pos = 0 ) const noexcept;

如果我想检查一个字符是否存在于std::string 中,从性能上看,哪个是首选?

【问题讨论】:

  • 我建议简单地分析与您的绩效衡量相关的两者。
  • 这些功能不是“有点不同”吗?
  • 看来MSVC++2015通过调用find(ch, pos)实现了find_first_of(CharT ch, size_type pos = 0),所以那里应该是一样的。
  • @VTT 是的,但问题仅集中在这两个签名上。答案由 LRiO 提供

标签: c++ string algorithm performance stl


【解决方案1】:

它们几乎相同。但在某些特定情况下不做完全相同的事情,这取决于您使用的标准库。

我正在使用一种叫做 EWL 的东西,(很可能没有人再使用它了)在那个库中 string::find()string::find_first_of 是相同的。

但是不同的图书馆有不同的故事。在某些库中,例如 Gnu、C++2a,如果您从空字符串中搜索空字符串,std::find() 返回位置 0。但是 std::find_first_of() 返回 std::string::npos。他们是对是错取决于你有不同的看法。

已在here 讨论该问题。

【讨论】:

    【解决方案2】:

    没关系。他们做同样的事情。

    就像,字面意思。 libstdc++ just delegates find_first_of(char, size_t) to find(char, size_t)as does libc++ 和 MSVS 2015(感谢 roalz)。任何实现都没有理由这样做。

    我不太清楚为什么find_first_of 的过载甚至存在;它可能只是为了与find 对称(当您使用其他重载时,它会做一些不同的事情),但老实说,这让我感到困惑。

    【讨论】:

      猜你喜欢
      • 2016-12-10
      • 2012-02-21
      • 2012-12-05
      • 2011-12-15
      • 2010-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多