我有一个关于使用std::search
vs string::find
来处理字符串的问题。我知道使用类特定成员函数算法通常比标准库算法更好,因为它可以根据类进行优化,但我想知道是否合理,为了保持一致性,使用{{1}使用迭代器而不是带有索引的std::search
。
对我来说做这样的事情会不会是一种罪过,还是应该坚持使用string :: find?在性能或风格方面,是否有任何巨大优势?
答案 0 :(得分:9)
现在(2017年4月27日),至少GCC libstdc++
(默认情况下也由clang使用)通过线性搜索实现std::string::find
,因此比使用
std::string_view substr{"whatever"};
auto it = std::search(s.cbegin(), s.cend(),
std::boyer_moore_searcher(substr.begin(), substr.end()));
问题在于Boyer-Moore搜索器为内部数据结构分配内存,因此可能会因std::bad_alloc
异常而失败。但是,std::string::find
已标记为noexcept
,因此使用std::string::find
内已实施的Boyer-Moore搜索者并非直截了当。
答案 1 :(得分:5)
string :: find使用线性搜索,但在某些情况下(使用最新补丁),它比Boyer Moore快几倍。我向libstdc ++和libc ++提交了一个补丁,它改进了string :: find。您可以尝试最近的gcc(7.1),您将获得改进的性能。您还可以使用我编写的简单基准测试套件来衡量性能 www.github.com/hiraditya/std-benchmark
特别是对于较小的字符串,当Boyer Moore忙于构建内部数据结构时,将完成(子)线性字符串:: find。另外,对于解析大多数搜索不匹配的HTML等,string :: find应该更快。
commit fc7ebc4b8d9ad7e2891b7f72152e8a2b7543cd65
Author: redi <redi@138bc75d-0d04-0410-961f-82ee72b054a4>
Date: Mon Jan 9 13:05:58 2017 +0000
PR66414 optimize std::string::find
2017-01-09 Jonathan Wakely <jwakely@redhat.com>
Aditya Kumar <hiraditya@msn.com>
PR libstdc++/66414
* include/bits/basic_string.tcc
(basic_string::find(const CharT*, size_type, size_type)): Optimize.
git-svn-id: svn+ssh://gcc.gnu.org/svn/gcc/trunk@244225 138bc75d-0d04-0410-961f-82ee72b054a4
PS:使用std :: find将始终比当前实现的当前std :: string :: find慢。