fork(1) download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. template <typename InIt1, typename InIt2>
  5. bool is_subsequence(InIt1 first1, InIt1 last1, InIt2 first2, InIt2 last2)
  6. {
  7. if (first2 == last2) {
  8. return false; // sub empty (should this return true?)
  9. }
  10. for (; first1 != last1; ++first1) {
  11. if (*first1 == *first2) {
  12. if (++first2 == last2) {
  13. return true; // sub exhausted
  14. }
  15. }
  16. }
  17. return false; // seq exhausted
  18. }
  19.  
  20. int main()
  21. {
  22. std::vector<int> a = { 1, 2, 3, 4 }, b = { 2, 4 }, c = { 4, 2 };
  23. std::vector<int> d = { 3, 6, 3, 1, 2, 3 }, e = { 3, 1, 3 };
  24.  
  25. std::cout << is_subsequence(a.begin(), a.end(), b.begin(), b.end()) << '\n';
  26. std::cout << is_subsequence(a.begin(), a.end(), c.begin(), c.end()) << '\n';
  27. std::cout << is_subsequence(d.begin(), d.end(), e.begin(), e.end()) << '\n';
  28. }
  29.  
  30.  
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
1
0
1