Function for checking if one array is a subset of another

My goal is to find out whether one array is a subset of another, in the same order but not necessarily consecutively. For example:
string major[10] = { "a", "b", "c", "f", "b"}
string major[10] = { "b", "f"}
Would return true but if the second array was
{"c", "a"} would return false.

 ``12345678910111213141516171819202122`` ``````bool subsequence(const string a1[], int n1, const string a2[], int n2) { for (int i = 0; i < n1; i++) { for (int j = 0; j < n2; j++) if (a1[j] == a2[i]) //i want to cycle through a1[] to see if a component matches a component of a2 { if ((j == n2-1) && (a1[i] == a2[j])) { return true; } } else { return false; } } }``````
Generalized to allow any container holding any type:
 ``12345678910111213141516171819202122232425262728293031`` ``````#include #include #include template bool subsequence (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2) { while (first2 != last2) { ForwardIterator1 it = std::find (first1, last1, *first2); if (it == last1) return false; ++first2; first1 = it; } return true; } int main() { std::string A[] = {"a", "b", "c", "f", "b"}; std::string B[] = {"b", "f"}; std::string C[] = {"c", "a"}; if (subsequence (A, A+5, B, B+2)) std::cout << "B is a subsequence of A." << std::endl; else std::cout << "B is not a subsequence of A." << std::endl; if (subsequence (A, A+5, C, C+2)) std::cout << "C is a subsequence of A." << std::endl; else std::cout << "C is not a subsequence of A." << std::endl; std::cin.get(); }``````

Output:
 ``12`` ``````B is a subsequence of A. C is not a subsequence of A.``````

Last edited on
Cannot use algorithm library, must write the function from scratch.
Use myFind instead of std::find then:
 ``1234567891011`` ``````template InputIterator myFind (InputIterator first, InputIterator last, const T& val) { while (first != last) { if (*first == val) return first; ++first; } return last; } ``````

Now replace
`ForwardIterator1 it = std::find (first1, last1, *first2);`
with
 `` `` ``ForwardIterator1 it = myFind (first1, last1, *first2);``
Last edited on
Topic archived. No new replies allowed.