1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
|
// Example program
#include <iostream>
#include <vector>
#include <algorithm>
using std::size_t;
template <typename T>
std::ostream& print_elements(std::ostream& os, const std::vector<T>& vec, size_t start_index, size_t end_index)
{
if (vec.size() == 0 || end_index == 0)
return os;
for (size_t i = start_index; i < end_index-1; i++)
{
os << vec[i] << ",";
}
return os << vec[end_index-1];
}
template <typename T>
std::ostream& print_elements(std::ostream& os, const std::vector<T>& vec)
{
return print_elements(os, vec, 0, vec.size());
}
template <typename T>
bool match_begin(std::vector<T> vec_A, std::vector<T> vec_B, size_t A_offset)
{
for (size_t i = 0; i < vec_A.size() - A_offset; i++)
{
if (vec_A[i + A_offset] != vec_B[i])
return false;
}
return true;
}
//
template <typename T>
bool match_end(std::vector<T> vec_A, std::vector<T> vec_B, size_t A_offset)
{
size_t start_offset = vec_B.size() - vec_A.size() + A_offset;
for (size_t i = start_offset; i < vec_B.size(); i++)
{
if (vec_A[i - start_offset] != vec_B[i])
return false;
}
return true;
}
template <typename T>
bool match_middle(std::vector<T> vec_A, std::vector<T> vec_B, size_t A_offset)
{
for (size_t i = 0; i < vec_A.size(); i++)
{
if (vec_A[i] != vec_B[i + A_offset])
return false;
}
return true;
}
void print_matches(const std::vector<int>& vec_A, const std::vector<int>& vec_B)
{
for (size_t i = 1; i < vec_A.size(); i++) // i [ 1, 2, 3 ]
{
if (match_begin(vec_A, vec_B, i))
{
std::cout << 0 << " = ";
print_elements(std::cout, vec_A, i, vec_A.size()) << "\n";
}
}
for (size_t i = 0; i < vec_B.size() - vec_A.size(); i++)
{
if (match_middle(vec_A, vec_B, i))
{
std::cout << i << " = ";
print_elements(std::cout, vec_A) << "\n";
}
}
for (size_t i = 1; i < vec_A.size(); i++)
{
if (match_end(vec_A, vec_B, i))
{
std::cout << vec_B.size() - vec_A.size() + i << " = ";
print_elements(std::cout, vec_A, 0, vec_A.size() - i) << "\n";
}
}
}
int main()
{
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
std::vector<int> vec_B { 4,4,3,1,2,4,2,0,5,8, 4, 4, 3, 1, 1, 1, 1, 8, 4, 4, 3, 0, 0, 8, 4 };
std::vector<int> vec_A { 8,4,4,3 };
print_matches(vec_A, vec_B);
}
|