fork(1) download
  1. #include <algorithm>
  2. #include <iterator>
  3. #include <vector>
  4. #include <iostream>
  5.  
  6.  
  7. template <class InputIt, class OutputIt>
  8. OutputIt copy_n_max(InputIt begin, InputIt end, OutputIt last, size_t count)
  9. {
  10. return std::copy_if(begin,
  11. end,
  12. last,
  13. [&count](typename std::iterator_traits<InputIt>::reference) -> bool
  14. {
  15. if (count > 0)
  16. {
  17. --count;
  18. return true;
  19. }
  20. return false;
  21. });
  22. }
  23.  
  24. int main(int, char const *[])
  25. {
  26. {
  27. std::vector<long> input{ 1, 2, 3, 4, 5, 6};
  28. std::vector<long> output_short;
  29. std::vector<long> output_long;
  30.  
  31. copy_n_max(input.begin(), input.end(), std::back_inserter(output_short), 3);
  32. copy_n_max(input.begin(), input.end(), std::back_inserter(output_long), input.size());
  33.  
  34. std::cout << output_short.size() << std::endl;
  35. std::cout << output_long.size() << std::endl;
  36. }
  37.  
  38. {
  39. std::vector<bool> input{ true, true, true, true, false };
  40. std::vector<bool> output_short;
  41. std::vector<bool> output_long;
  42.  
  43. copy_n_max(input.begin(), input.end(), std::back_inserter(output_short), 3);
  44. copy_n_max(input.begin(), input.end(), std::back_inserter(output_long), input.size());
  45.  
  46. std::cout << output_short.size() << std::endl;
  47. std::cout << output_long.size() << std::endl;
  48. }
  49. return 0;
  50. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
3
6
3
5