fork download
  1. #include <iostream>
  2. #include <iterator>
  3. #include <vector>
  4. #include <algorithm>
  5.  
  6. template <class InputIterator1, class InputIterator2,
  7. class OutputIterator>
  8. OutputIterator merge_alternately ( InputIterator1 first1, InputIterator1 last1,
  9. InputIterator2 first2, InputIterator2 last2,
  10. OutputIterator result)
  11. {
  12. size_t ct(0);
  13. while(first1 != last1
  14. and first2 != last2)
  15. *result++ = (++ct % 2 ? *first1++ : *first2++);
  16.  
  17. std::copy(first1, last1, result);
  18. std::copy(first2, last2, result);
  19.  
  20. return result;
  21. }
  22.  
  23. int main()
  24. {
  25.  
  26. std::vector<int> const a{1, 2, 3, 4, 5,},
  27. b{6, 7, 8, 9, 10};
  28. std::vector<int> c;
  29.  
  30. merge_alternately(a.begin(), a.end(),
  31. b.begin(), b.end(),
  32. std::back_inserter(c));
  33.  
  34. std::copy(c.begin(), c.end(), std::ostream_iterator<int>(std::cout, ", "));
  35. }
Success #stdin #stdout 0s 3016KB
stdin
Standard input is empty
stdout
1, 6, 2, 7, 3, 8, 4, 9, 5, 10,