c++ - STL中使用了哪种字符串匹配算法?

标签 c++ string algorithm stl stdstring

c++ STL std::string.find()中的字符串匹配算法是用哪个? 一直在研究字符串匹配算法,想知道STL c++用的是哪一种。

最佳答案

std::string.find() 的字符串匹配算法没有标准规定,依赖于实现。您可以阅读实现的源代码以查找使用了哪一个。

对于 GCC,您可能希望查看文件 basic_string.tcc .该文件中的 find() 部分是:

00736   template<typename _CharT, typename _Traits, typename _Alloc>
00737     typename basic_string<_CharT, _Traits, _Alloc>::size_type
00738     basic_string<_CharT, _Traits, _Alloc>::
00739     find(const _CharT* __s, size_type __pos, size_type __n) const
00740     {
00741       __glibcxx_requires_string_len(__s, __n);
00742       const size_type __size = this->size();
00743       const _CharT* __data = _M_data();
00744 
00745       if (__n == 0)
00746     return __pos <= __size ? __pos : npos;
00747 
00748       if (__n <= __size)
00749     {
00750       for (; __pos <= __size - __n; ++__pos)
00751         if (traits_type::eq(__data[__pos], __s[0])
00752         && traits_type::compare(__data + __pos + 1,
00753                     __s + 1, __n - 1) == 0)
00754           return __pos;
00755     }
00756       return npos;
00757     }

关于c++ - STL中使用了哪种字符串匹配算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30409141/

相关文章:

python - 以两个(或更多)其他变量为条件指定 `str` 的更优雅方式

c++ - 如何检查一个字符串是否表示一个正的非零整数?

c++ - 如何在 gdb 中为函数的所有调用设置断点?

C++:按 vector 大小重载函数

c++ - 这是用组合 vector 类重载 [] 的正确方法吗

algorithm - 有没有办法从文件中存储 gzip 的字典?

algorithm - 算法解释的线性复杂度

c++ - 带空格的 Cin 和 ","

c# - 删除字符串数组开头的字符

algorithm - 哈夫曼树 : card guessing game