for_each und ostreams
-
hi,
ich möchte einen container mit for_each ausgeben. wie mach ich am geschicktesten das funktionsobjekt? einfach eine referenz auf den ostream speichern*? oder geht das irgendwie besser?
*also so in der art:
class printer { private: std::ostream & o; public: printer( std::ostream &out ) : o( out ) {} }
-
für sowas ist ostream_iterator und copy
-
b7f7 schrieb:
für sowas ist ostream_iterator und copy
entweder so oder allgemeiner
#include <iostream> #include <vector> #include <algorithm> using namespace std; struct printer { void operator() (int i) { cout << i << " "; } }; int main() { printer p; vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); for_each( v.begin(), v.end(), p ); }Kurt
-
wenn du den stream als parameter haben wllst, dann kannst du es so machen:
#include <iostream> #include <vector> #include <algorithm> using namespace std; class printer { ostream &out; public: printer (ostream &o) : out(o) {} ~printer () {} void operator() (int i) { out << i << " "; } }; int main() { vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); for_each( v.begin(), v.end(), printer(cout)); // printer(cout) ist ein konstruktor-aufruf }
-
du kannst auch member-templates benutzen:
#include <iostream> #include <vector> #include <algorithm> #include <string> using namespace std; class printer { ostream &out; public: printer (ostream &o) : out(o) {} ~printer () {} template<class T> void operator() (T i) { out << i << " "; } }; int main() { vector<string> v; v.push_back("str1"); v.push_back("str2"); v.push_back("str3"); v.push_back("str4"); for_each( v.begin(), v.end(), printer(cout)); // printer(cout) ist ein konstruktor-aufruf }dann kannst du mit printer jeden datentyp ausgeben, für den ein << operator definiert ist.
-
ok, danke @all, habs jetzt so ähnlich gemacht.
b7f7 schrieb:
für sowas ist ostream_iterator und copy
? ostream_iterator ist klar, aber was soll "copy" bedeuten?
edit: ach so, ja, ist klar
-
#include <iterator> // ... std::copy (v.begin (), v.end (), std::ostream_iterator<char> (o), std::ostream_iterator<char> ());Mit o als deinen eigenen ostream.
-
.filmor schrieb:
#include <iterator> // ... std::copy (v.begin (), v.end (), std::ostream_iterator<char> (o), std::ostream_iterator<char> ());Es gibt kein copy mit 4 Parametern. Und wenn es dies gäbe, wäre der 4. redundant.
#include <algorithm> // std::copy #include <iterator> // std::ostream_iterator // ... std::copy( v.begin(), v.end(), std::ostream_iterator< char >( o ) ); // o ist ein std::ostream.. reicht aus.
Gruß
Werner