I am trying to find a simple way to check whether a vector is a subset of another without sorting the order of elements in the vector. Both the vectors contain random number
My answer assumes that when you say "subset", you are really searching more for the equivalent of a "substring"; that is, maintaining order of elements during the search.
Ultimately, I can't see how you could do this in anything less than O(n*m)
. Given that, you can just roll your own pretty simply:
template
bool contains(std::vector const& a, std::vector const& b) {
for (typename std::vector::const_iterator i = a.begin(), y = a.end(); i != y; ++i) {
bool match = true;
typename std::vector::const_iterator ii = i;
for (typename std::vector::const_iterator j = b.begin(), z = b.end(); j != z; ++j) {
if (ii == a.end() || *j != *ii) {
match = false;
break;
}
ii++;
}
if (match)
return true;
}
return false;
}
Live demo.
(You could probably be more creative with the template parameters.)