Boyer-Moore and Boyer-Moore-Horspool are two efficient search algorithms provided by the C++ standard library.
Both are designed for substring searches and can be significantly faster than a simple linear search, especially for large texts.
The Boyer-Moore algorithm is known for its efficiency in practice. It preprocesses the pattern to create two tables that are used to skip sections of the text, making the search faster.
The following example shows how we can use std::boyer_moore_searcher
:
#include <algorithm>
#include <functional>
#include <iostream>
#include <string>
int main() {
std::string text = "Lorem ipsum dolor sit"
" amet, consectetur adipiscing elit.";
std::string pattern = "dolor";
std::boyer_moore_searcher searcher(
pattern.begin(), pattern.end());
auto result = std::search(
text.begin(), text.end(), searcher);
if (result != text.end()) {
std::cout << "Pattern found at position "
<< std::distance(text.begin(), result);
} else {
std::cout << "Pattern not found";
}
}
Pattern found at position 12
The Boyer-Moore-Horspool algorithm is a simplified version of the Boyer-Moore algorithm. It only uses one table for preprocessing, which makes it simpler and sometimes faster for certain types of input.
The following example shows how we can use std::boyer_moore_horspool_searcher
:
#include <algorithm>
#include <functional>
#include <iostream>
#include <string>
int main() {
std::string text = "Lorem ipsum dolor sit amet,"
" consectetur adipiscing elit.";
std::string pattern = "dolor";
std::boyer_moore_horspool_searcher searcher(
pattern.begin(), pattern.end());
auto result = std::search(
text.begin(), text.end(), searcher);
if (result != text.end()) {
std::cout << "Pattern found at position "
<< std::distance(text.begin(), result);
} else {
std::cout << "Pattern not found";
}
}
Pattern found at position 12
In summary, both algorithms are powerful tools for efficient substring searches. Your choice between them should depend on the specific requirements of your text data and pattern length.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to the 8 main searching algorithms in the C++ standard library, including find()
, find_if()
, find_if_not()
, find_first_of()
, adjacent_find()
, search_n()
, search()
, and find_end()
.