我想知道是否可以将一个数组{67,55,65}
查找到另一个数组{23,45,67,55,65,66,76,78}
中。我不感兴趣的是寻找数组的单个元素,而是数组作为一个整体。我试过一些代码
#include <iostream>
#include <algorithm>
#include <array>
int main()
{
std::array<int,8> in = {23,45,67,55,65,66,76,78};
std::array<int,3> sstr = {67,55,65};
auto it = std::search(in.begin(), in.end(),
std::make_boyer_moore_searcher(
sstr.begin(), sstr.end()));
if(it != in.end())
std::cout << "The string " << sstr << " found at offset "
<< it - in.begin() << '\n';
else
std::cout << "The string " << sstr << " not found\n";
}
编辑:使用make_boyer_moore_searcher
的原因是我的数组的大小,粗略计算,可能是大约1000万。我想要一种高效的搜索技术。
我不确定我的代码是否应该工作。我有很多错误
bm.cpp:12:20:error:“make_boyer_moore_searcher”不是“std”std::make_boyer_moore_searcher的成员(^bm.cpp:15:19:error:无法将“std::basic_ostream”lvalue绑定到“std::basic_ostream&”std::cout<<“在偏移量处找到的字符串”^,该字符串包含在从/usr/include/C++/4.8/iostream:39:0,从_traits=std::char_traits;_tp=std::array]'operator<<(basic_ostream<_chart,_traits>&__os,const_tp&__x)^bm.cpp:18:19:error:无法将'std::basic_ostream'lvalue绑定到'std::basic_ostream&&'std::cout<<“字符串”<
如果要使用make_boyer_moore_searcher
,则应包括正确的头,如参考页面中所述:
#include <experimental/algorithm>
#include <experimental/functional>
那么,由于那些不属于std
,您应该使用以下方法调用它们:
auto it = std::experimental::search(in.begin(), in.end(),
std::experimental::make_boyer_moore_searcher(
sstr.begin(), sstr.end()));
在您的代码中,您还尝试使用运算符<<
打印出int
的std::array
(您称之为string)。您可以重载它或改用循环:
for ( int i : sstr ) {
std::cout << i << ' ';
}
通过您的数据,您应该获得:
The string 67 55 65 found at offset 2
删除make_boyer_moore_searcher
,只使用std::search
。测试它
#include <iostream>
#include <algorithm>
#include <array>
int main()
{
std::array<int,8> in = {23,45,67,55,65,66,76,78};
std::array<int,3> sstr = {67,55,65};
auto it = std::search(in.begin(), in.end(), sstr.begin(), sstr.end());
if(it != in.end())
std::cout << "The string found at offset "
<< it - in.begin() << '\n';
else
std::cout << "The string not found\n";
}
编辑:
作为对注释的响应,还可以搜索一个2D数组。在std::search
中,使用运算符==
比较元素。因此在本例中,您可以通过将代码更改为:
std::array<std::array<int, 3>, 4> in {{ {1,2,3}, {4,5,6}, {7,8,9}, {10,11,12} }};
std::array<std::array<int,3>, 1> sstr = {10,11,12};
...
测试它