gpt4 book ai didi

c++ - 在 `std::search` 上使用 `string::find`

转载 作者:可可西里 更新时间:2023-11-01 15:51:50 24 4
gpt4 key购买 nike

我有一个关于使用 std::searchstring::find 处理字符串的问题。我知道使用特定于类的成员函数算法通常比标准库算法更好,因为它可以基于类进行优化,但我想知道为了一致性,使用 std 是否合理::search 使用迭代器而不是 string::find 使用索引。

做那样的事情对我来说是一种罪过还是我应该坚持使用 string::find?两者在性能或风格方面是否有任何巨大优势?

最佳答案

现在(2017 年 4 月 27 日),至少 GCCs 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 搜索器> 不是直截了当的。

关于c++ - 在 `std::search` 上使用 `string::find`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43657530/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com