fork download
  1. #include <iostream>
  2. #include <iterator>
  3. #include <vector>
  4. #include <algorithm>
  5.  
  6. template <class T,
  7. class charT = char,
  8. class traits = std::char_traits<charT> >
  9. class my_infix_ostream_iterator :
  10. public std::iterator<std::output_iterator_tag, void, void, void, void>
  11. {
  12. std::basic_ostream<charT, traits> *os;
  13. charT const* delimiter;
  14. size_t counter, numPerLine;
  15.  
  16. public:
  17. typedef charT char_type;
  18. typedef traits traits_type;
  19. typedef std::basic_ostream<charT,traits> ostream_type;
  20.  
  21. my_infix_ostream_iterator(ostream_type& s, size_t numPerLine = 0, charT const *d = 0)
  22. : os(&s), delimiter(d), numPerLine(numPerLine), counter(0)
  23. {}
  24.  
  25. my_infix_ostream_iterator& operator=(T const &item)
  26. {
  27. if (counter > 0)
  28. {
  29. if (delimiter)
  30. *os << delimiter;
  31. if ((numPerLine > 0) && ((counter % numPerLine) == 0))
  32. *os << os->widen('\n');
  33. }
  34. *os << item;
  35. ++counter;
  36. return *this;
  37. }
  38.  
  39. my_infix_ostream_iterator& operator*() {
  40. return *this;
  41. }
  42.  
  43. my_infix_ostream_iterator& operator++() {
  44. return *this;
  45. }
  46.  
  47. my_infix_ostream_iterator& operator++(int) {
  48. return *this;
  49. }
  50. };
  51.  
  52. struct myClass
  53. {
  54. int value;
  55. };
  56.  
  57. std::ostream& operator<<(std::ostream &os, const myClass &cls)
  58. {
  59. os << cls.value;
  60. return os;
  61. }
  62.  
  63. int main()
  64. {
  65. std::vector<myClass> myVec = {
  66. {1}, {2}, {3}, {4}, {5},
  67. {6}, {7}, {8}, {9}, {10},
  68. {11}, {12}, {13}
  69. };
  70.  
  71. std::cout << "Using a for loop..." << std::endl;
  72.  
  73. my_infix_ostream_iterator<myClass> iter(std::cout, 5, ", ");
  74. for (const auto &elem : myVec) {
  75. *iter++ = elem;
  76. }
  77.  
  78. std::cout << std::endl << std::endl;
  79.  
  80. std::cout << "Using std::copy()..." << std::endl;
  81.  
  82. std::copy(myVec.begin(), myVec.end(),
  83. my_infix_ostream_iterator<myClass>(std::cout, 5, ", ")
  84. );
  85.  
  86. return 0;
  87. }
Success #stdin #stdout 0s 4352KB
stdin
Standard input is empty
stdout
Using a for loop...
1, 2, 3, 4, 5, 
6, 7, 8, 9, 10, 
11, 12, 13

Using std::copy()...
1, 2, 3, 4, 5, 
6, 7, 8, 9, 10, 
11, 12, 13