473,397 Members | 1,960 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,397 software developers and data experts.

Iterating and printing

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

Apr 6 '07 #1
5 1948
mi********@googlemail.com wrote:
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
[..]
Any thoughts on the matter would be greatly appreiciated!
Have you tried using 'ostream_iterator'? It should work well with
both 'cout' and any stringstream you can create.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Apr 6 '07 #2
On 2007-04-06 14:17, mi********@googlemail.com wrote:
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
Don't know about for_each but std::copy can be quite useful together
with ostream_iterator mentioned by Victor:

int main()
{
std::vector<intvec;
for (int i = 0; i < 10; ++i)
vec.push_back(i);

std::stringstream ss;
std::copy(vec.begin(), vec.end(),
std::ostream_iterator<int>(ss, " "));
std::copy(vec.begin(), vec.end(),
std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n" << ss.str() << "\n";
return 0;
}

--
Erik Wikström
Apr 6 '07 #3
On 6 Apr, 14:58, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
mikehul...@googlemail.com wrote:
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

[..]
Any thoughts on the matter would be greatly appreiciated!

Have you tried using 'ostream_iterator'? It should work well with
both 'cout' and any stringstream you can create.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Thanks Victor, I will give that a go!

Apr 6 '07 #4
On 6 Apr, 15:30, Erik Wikström <Erik-wikst...@telia.comwrote:
On 2007-04-06 14:17, mikehul...@googlemail.com wrote:
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

Don't know about for_each but std::copy can be quite useful together
with ostream_iterator mentioned by Victor:

int main()
{
std::vector<intvec;
for (int i = 0; i < 10; ++i)
vec.push_back(i);

std::stringstream ss;
std::copy(vec.begin(), vec.end(),
std::ostream_iterator<int>(ss, " "));
std::copy(vec.begin(), vec.end(),
std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n" << ss.str() << "\n";
return 0;

}

--
Erik Wikström
Thanks Erik, I'll give it a try!

Apr 6 '07 #5
On Apr 6, 2:17 pm, "mikehul...@googlemail.com"
<mikehul...@googlemail.comwrote:
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
Forget for_each. It doesn't buy you anything here. (You can
use it, but you end up writing more code than if you wrote the
loop manually.)
stringstream s;
for( collection<C>::iterator it = Collection.begin(); it !=
Collection.end(); it++)
{
cout << *it;
s << *it;}
You don't really want to output to both streams in the same
loop, do you? And doubtlessly, you'll need a separator or some
other formatting structure as well.

Typically, I'd encapsulate the container in a class of my own
anyway, and then add something like:

std::ostream&
operator<<( std::ostream& dest, ContainerC const& source )
{
dest << '[' ;
for ( ContainerC::iterator it = source.begin() ;
it != source.end() ;
++ it ) {
if ( it != source.begin() ) {
dest << ", " ;
}
dest << *it ;
}
dest << ']' ;
return dest ;
}

As you can see, there's a bit more to it than just iterating
over the values; handling the separator is particularly
bothersome; the std::ostream_iterator got it wrong, and for that
reason are practically useless.
This seems like a fairly common task!
It is, but since formatting is so specific, it tends to be
written out explicitly each time it's needed.

--
James Kanze (Gabi Software) email: ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 6 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Patrick von Harsdorf | last post by:
I want to iterate over a collection and delete all unwanted entries. for item in collection: del item of course doesn´t do anything useful. Two things come to mind: a) iterating backwards...
4
by: Fernando Rodríguez | last post by:
Hi, While iterating through a list I'd like to know not just the current element, but also its index. Is there a better way than this: i = 0 newList = for element in aList:...
7
by: Dave Hansen | last post by:
OK, first, I don't often have the time to read this group, so apologies if this is a FAQ, though I couldn't find anything at python.org. Second, this isn't my code. I wouldn't do this. But a...
6
by: Gustaf Liljegren | last post by:
I ran into this problem today: I got an array with Account objects. I need to iterate through this array to supplement the accounts in the array with more data. But the compiler complains when I...
1
by: Kyle Walz | last post by:
I'm working on an app where each page is a like a form (not Windows form) with a set format. Using MSVB.NET 2003 with 1.1 framework. Here's some code: Private Sub PrintText(ByVal sender As...
2
by: Nick | last post by:
Hi all, Just a quick question. I have a class that exposes a number of fields (which are themselves custom types) through public properties. At run time, I have an object whom I'd like to...
2
by: CamelR | last post by:
I have a newbie question, and I have seen reference to this mentioned in many places, but all just say "this has been discussed frequently in (other places) so we won't discuss it here..." and I am...
9
by: krbyxtrm | last post by:
hello i have this profile for iterating empty vectors: +0.3us (microsecond) delay on intel pentium 2.4Ghz can this added delay to my application be reduced? i mean near zero delay, its very...
4
RMWChaos
by: RMWChaos | last post by:
The next episode in the continuing saga of trying to develop a modular, automated DOM create and remove script asks the question, "Where should I put this code?" Alright, here's the story: with a...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.