M
mikehulluk
Ok,
Imagine I have a class
class C
{
};
ostream& operator<<(ostream& o, const C& c) { ...}
I have a collection of these objects, in an STL list or vector and
want to do 2 things:
1/ Print all these objects to cout
2/ Write all these objects to a long string
Now, I wanted to try and use for_each and avoid my usual code of
stringstream s;
for( collection<C>::iterator it = Collection.begin(); it !=
Collection.end(); it++)
{
cout << *it;
s << *it;
}
string res = s.str();
So I tried a couple of options:
void printC(ostream& o, const C& c) { o << c;}
for_each( Collection.begin(), Collection.end(),
bind1st( fun_ptr( printC), cout) );
which wouldn't work because of a problem of refs to refs,
so i started on the second problem and created a class
class P
{
public:
P() { //Setup code }
stringstream s;
string getString(){ return s.str();}
void operator()(const C& c) { s << c; }
};
and tried to pass this:
P p;
for_each( Collection.begin(), Collection.end(), p );
which fails because we can't copy P, because it contains a
stringstream which can't be copied.
So i currently have
class Q
{
string s;
void operator()(const C& c) { stringstream ss; ss << c; s+=
ss.str(); }
};
Q q;
for_each( Collection.begin(), Collection.end(), q );
which, correct me if i'm wrong, seems like a very crude way of doing
it!
This seems like a fairly common task!
Any thoughts on the matter would be greatly appreiciated!
Michael
Imagine I have a class
class C
{
};
ostream& operator<<(ostream& o, const C& c) { ...}
I have a collection of these objects, in an STL list or vector and
want to do 2 things:
1/ Print all these objects to cout
2/ Write all these objects to a long string
Now, I wanted to try and use for_each and avoid my usual code of
stringstream s;
for( collection<C>::iterator it = Collection.begin(); it !=
Collection.end(); it++)
{
cout << *it;
s << *it;
}
string res = s.str();
So I tried a couple of options:
void printC(ostream& o, const C& c) { o << c;}
for_each( Collection.begin(), Collection.end(),
bind1st( fun_ptr( printC), cout) );
which wouldn't work because of a problem of refs to refs,
so i started on the second problem and created a class
class P
{
public:
P() { //Setup code }
stringstream s;
string getString(){ return s.str();}
void operator()(const C& c) { s << c; }
};
and tried to pass this:
P p;
for_each( Collection.begin(), Collection.end(), p );
which fails because we can't copy P, because it contains a
stringstream which can't be copied.
So i currently have
class Q
{
string s;
void operator()(const C& c) { stringstream ss; ss << c; s+=
ss.str(); }
};
Q q;
for_each( Collection.begin(), Collection.end(), q );
which, correct me if i'm wrong, seems like a very crude way of doing
it!
This seems like a fairly common task!
Any thoughts on the matter would be greatly appreiciated!
Michael