在c ++ stl std :: string.find()中用作字符串匹配算法? 我一直在研究字符串匹配算法,并想知道stl c ++使用了哪一种。
答案 0 :(得分:3)
STL不指定实现,而是指定接口和约束,包括复杂性约束。
因此,例如,它不会说std::map
必须是一个红黑树,但它确实指出搜索是最坏情况的对数;如果你阅读复杂性约束,你可以看到它必须是一个平衡的树。
如果你看一下str::find
的复杂性,你可以看到"未指定,但通常长度达到线性() - pos乘以匹配的序列长度(最差情况)。 #34;,所以它基本上允许(但不指定)朴素算法。
您所引用的家庭的实现虽然在this boost library中。
答案 1 :(得分:3)
std :: string.find()的字符串匹配算法未由starndard指定,并且与实现有关。您可以阅读实现的源代码以找到使用的实现。
对于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 }
答案 2 :(得分:-1)
除了关联容器的方法之外,其名称中包含单词find
的所有标准算法都使用顺序搜索。