fork download
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <iterator>
  4. #include <vector>
  5. #include <stdexcept>
  6.  
  7. template<typename InputIt, typename OutputIt>
  8. OutputIt copy_every_nth(InputIt first, InputIt last, OutputIt d_first, size_t nth) {
  9. if (nth == 0) {
  10. throw std::invalid_argument("copy_nth: nth can't be 0");
  11. }
  12.  
  13. size_t counter = 0;
  14.  
  15. auto pred = [&counter, nth]
  16. (const typename std::iterator_traits<InputIt>::value_type &) -> bool {
  17.  
  18. return !(counter++ % nth);
  19. };
  20.  
  21. return std::copy_if(first, last, d_first, pred);
  22. }
  23.  
  24. int main() {
  25. size_t nth = 0;
  26.  
  27. std::cin >> nth;
  28.  
  29. std::vector<int> v1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
  30. std::vector<int> v2;
  31.  
  32. copy_every_nth(v1.begin(), v1.end(), std::back_inserter(v2), nth);
  33.  
  34. std::copy(v2.begin(), v2.end(), std::ostream_iterator<int>(std::cout, " "));
  35.  
  36. return 0;
  37. }
Success #stdin #stdout 0s 3068KB
stdin
2
stdout
0 2 4 6 8