c++ - Accumulating into std::ostream using std::accumulate -


i trying use std::accumulate write std::ostream in operator<< (this minimum example, know implemented simpler):

#include <iterator> #include <iostream> #include <algorithm> #include <functional> #include <vector>  struct {     a() : v(std::vector<int>()){};     std::vector<int> v;     a(std::vector<int> v) : v(v){};     friend std::ostream& operator<<(std::ostream& stream, a& a); };  std::ostream& operator<<(std::ostream& stream, a& a) { // need similar //    return std::accumulate(a.v.begin(), a.v.end(), "",                            std::ostream_iterator<int>(stream, " ")); // or: // return std::accumulate(a.v.begin(), a.v.end(), stream,                            []()->{}); }  int main(int argc, char* argv[]) {     std::vector<int> v({1, 2, 3, 4, 5});     a(v);     std::cout << << std::endl;      return 0; } 

how can make operator work?

it can done:

// using accumulate std::ostream& out_acc(const std::vector<int>& is, std::ostream& out) {     return std::accumulate(is.begin(),                            is.end(),                            std::ref(out),                            [](std::ostream& os, int i) -> std::ostream&                            { return os << << ", "; });  }  // using for_each std::ostream& out_for(const std::vector<int>& is, std::ostream& out) {     std::for_each(is.begin(),                     is.end(),                     [&](int i)                     { out << << ", "; });     return out;  } 

for_each natural choice, don't care accumulated value.


Comments