I'm trying to find subsequences of vector from a vector.
For example, if I want to find {2, 3} from {1, 2, 3, 1, 2, 3, 4}, the result should be {1, 4}.
Here's what I wrote so far.
vector<int> v1 = {1, 2, 3, 1, 2, 3, 4}; //source vector
vector<int> v2 = {2, 3}; //the subsequence to find
vector<size_t> founds; //positions found
for (size_t i=0; i<v1.size(); ++i) {
auto it = search(v1.begin()+i, v1.end(), v2.begin(), v2.end());
if (it != v1.end()) {
size_t pos = distance(v1.begin(), it);
founds.push_back(pos);
i += pos;
}
}
for (size_t i=0; i<founds.size(); ++i) {
cout << founds[i] << endl; //prints 1, 4
}
While this seems to work, I would appreciate any advice to make the code simpler and efficient.
EDIT : I updated the code based on @user1118321's advice.
Here's an updated code.
vector<int> source = {5, 8, 1, 2, 1, 2, 1, 2, 1}; //source vector
vector<int> toSearch = {1, 2, 1}; //the subsequence to find
vector<size_t> results; //positions found
const auto srcBegin = source.begin();
const auto srcEnd = source.end();
for (auto nextIndex = srcBegin; nextIndex < srcEnd; nextIndex++)
{
const auto it = search(nextIndex, srcEnd, toSearch.begin(), toSearch.end());
if (it != srcEnd) {
const size_t pos = distance(srcBegin, it);
results.push_back(pos);
nextIndex = srcBegin + pos;
}
}
for (size_t i=0; i<results.size(); ++i) {
cout << results[i] << endl; //prints 2, 4, 6
}
And if I want to ignore the overlapping copies of a subsequence, I can change nextIndex = srcBegin + pos;
to nextIndex = srcBegin + pos + toSearch.size();
Then it prints 2, 6
#include
lines, and amain()
that shows how to call your function. It's not mandatory, but it really helps! \$\endgroup\$