473,407 Members | 2,629 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,407 software developers and data experts.

applying a method to an array of objects.

I have created a class Particle which has a method toString() that
prints out all the useful information. In my main program I create an
array of these objects and once I've fiddled with them a bit I want to
use the toString() method on them all.
Is there a way of defining toString() so that I don't have to loop
through all of the particles printing each individually.

The code might explain it better than I can so the relevant part of the
class is below:

class particle{
string toString(){
ostringstream os;
os << pos.toString << '\t'
<< Vel.toString << '\t'
<< Npos.toString << '\t'
<< w.toString << '\n'
return os.str();
} ;
}

I then create some particles:

particle* myParticles = new particle[n];

and would like to be able to write

cout << myParticles.toString();

rather than:

for(int i;i<n;i++){
cout << myParticles[i].toString();
}

Jun 1 '06 #1
4 1668
On 2006-06-01 12:52, Cl*******@hotmail.com wrote:
I have created a class Particle which has a method toString() that
prints out all the useful information. In my main program I create an
array of these objects and once I've fiddled with them a bit I want to
use the toString() method on them all.
Is there a way of defining toString() so that I don't have to loop
through all of the particles printing each individually.

The code might explain it better than I can so the relevant part of the
class is below:

class particle{
string toString(){
ostringstream os;
os << pos.toString << '\t'
<< Vel.toString << '\t'
<< Npos.toString << '\t'
<< w.toString << '\n'
return os.str();
} ;
}

I then create some particles:

particle* myParticles = new particle[n];

and would like to be able to write

cout << myParticles.toString();

rather than:

for(int i;i<n;i++){
cout << myParticles[i].toString();
}


No, not if you just put them in an array. You could create your own
array-like container class to put them in and overload the []-operator
and such but to do all that just so that you don't have to write two
lines whenever you want to print the content is a bit much. A better
alternative would be to create a function with the for-loop and just
call the function with the array as argument.

Erik Wikström
--
"I have always wished for my computer to be as easy to use as my
telephone; my wish has come true because I can no longer figure
out how to use my telephone" -- Bjarne Stroustrup
Jun 1 '06 #2
good idea, thanks.
Erik Wikström wrote:
On 2006-06-01 12:52, Cl*******@hotmail.com wrote:
I have created a class Particle which has a method toString() that
prints out all the useful information. In my main program I create an
array of these objects and once I've fiddled with them a bit I want to
use the toString() method on them all.
Is there a way of defining toString() so that I don't have to loop
through all of the particles printing each individually.

The code might explain it better than I can so the relevant part of the
class is below:

class particle{
string toString(){
ostringstream os;
os << pos.toString << '\t'
<< Vel.toString << '\t'
<< Npos.toString << '\t'
<< w.toString << '\n'
return os.str();
} ;
}

I then create some particles:

particle* myParticles = new particle[n];

and would like to be able to write

cout << myParticles.toString();

rather than:

for(int i;i<n;i++){
cout << myParticles[i].toString();
}


No, not if you just put them in an array. You could create your own
array-like container class to put them in and overload the []-operator
and such but to do all that just so that you don't have to write two
lines whenever you want to print the content is a bit much. A better
alternative would be to create a function with the for-loop and just
call the function with the array as argument.

Erik Wikström
--
"I have always wished for my computer to be as easy to use as my
telephone; my wish has come true because I can no longer figure
out how to use my telephone" -- Bjarne Stroustrup


Jun 1 '06 #3
Erik Wikstr?m <Er***********@telia.com> wrote:
On 2006-06-01 12:52, Cl*******@hotmail.com wrote:
I have created a class Particle which has a method toString() that
prints out all the useful information. In my main program I create an
array of these objects and once I've fiddled with them a bit I want to
use the toString() method on them all.
Is there a way of defining toString() so that I don't have to loop
through all of the particles printing each individually.

The code might explain it better than I can so the relevant part of the
class is below:

class particle{
string toString(){
ostringstream os;
os << pos.toString << '\t'
<< Vel.toString << '\t'
<< Npos.toString << '\t'
<< w.toString << '\n'
return os.str();
} ;
}

I then create some particles:

particle* myParticles = new particle[n];

and would like to be able to write

cout << myParticles.toString();

rather than:

for(int i;i<n;i++){
cout << myParticles[i].toString();
}


No, not if you just put them in an array. You could create your own
array-like container class to put them in and overload the []-operator
and such but to do all that just so that you don't have to write two
lines whenever you want to print the content is a bit much. A better
alternative would be to create a function with the for-loop and just
call the function with the array as argument.


Another alternative is to use operator overloading. You can overload
operator<< for your type, something like (untested):

std::ostream& operator<<(std::ostream& os, const particle& p)
{
// The below is what it would look like if you have an
// appropriate operator<< for each member instead of using
// toString

os << pos << '\t'
<< Vel << '\t'
<< Npos << '\t'
<< w; // I usually leave off the last '\n' to mimic output
// other native types
return os;
}

(You may need to make it a friend function if it accesses private or
protected parts of your class).

If you do it this way, then you can do (for example):

particle p = /* whatever */;
// ...
o << p << '\n';

where 'o' can be any std::ostream, like std::cout or a std::ofstream.
In addition, this will let you use std::copy (in <algorithm>) for
output. Here is a complete example with a couple different uses:
#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>
#include <vector>

class Particle {
// dummy variables for illustration
std::string name_;
double vel_;
int pos_;

public:
Particle()
: name_("empty")
, vel_(0.0)
, pos_(42)
{ }

friend std::ostream& operator<<(std::ostream&, const Particle& p);
};

std::ostream& operator<<(std::ostream& os, const Particle& p)
{
os << p.name_ << '\t'
<< '(' << p.vel_ << ", "
<< p.pos_ << ')';

return os;
}

std::ostream& operator<<(std::ostream& os, const std::vector<Particle>& pv)
{
std::copy(pv.begin(), pv.end(), std::ostream_iterator<Particle>(os, "\n"));
return os;
}

int main()
{
int n = 3;
Particle* myParticles = new Particle[n];
// better would be std::vector

std::cout << "Array:\n";
std::copy(myParticles,
myParticles + n,
std::ostream_iterator<Particle>(std::cout, "\n"));
std::cout << "\nVector:\n";
std::vector<Particle> myParticles2(3);
std::copy(myParticles2.begin(),
myParticles2.end(),
std::ostream_iterator<Particle>(std::cout, "\n"));

std::cout << "\nVector2:\n";
std::cout << myParticles2;
}

--
Marcus Kwok
Replace 'invalid' with 'net' to reply
Jun 1 '06 #4
Marcus Kwok <ri******@gehennom.invalid> wrote:
int main()
{
int n = 3;
Particle* myParticles = new Particle[n];
// better would be std::vector

std::cout << "Array:\n";
std::copy(myParticles,
myParticles + n,
std::ostream_iterator<Particle>(std::cout, "\n"));
Ack! There should be a

delete[] myParticles;

here. This is why I avoid using raw dynamic arrays, and prefer
std::vector.
std::cout << "\nVector:\n";
std::vector<Particle> myParticles2(3);
std::copy(myParticles2.begin(),
myParticles2.end(),
std::ostream_iterator<Particle>(std::cout, "\n"));

std::cout << "\nVector2:\n";
std::cout << myParticles2;
}


--
Marcus Kwok
Replace 'invalid' with 'net' to reply
Jun 1 '06 #5

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

Similar topics

6
by: Matt Feinstein | last post by:
Is there an optimal way to apply a function to the elements of a two-d array? What I'd like to do is define some function: def plone(x): return x+1 and then apply it elementwise to a 2-D...
3
by: Christopher Jeris | last post by:
Please help me understand the differences, in semantics, browser support and moral preferredness, between the following three methods of swapping content in and out of a page via JavaScript. I...
6
by: Martin | last post by:
I'd like to be able to get the name of an object instance from within a call to a method of that same object. Is this at all possible? The example below works by passing in the name of the object...
2
by: craigkenisston | last post by:
Hi, I created an array of objects like this : object Values = {myObject.myprop, otherobject.otherprop, thirdobject.xprop}; Then I pass it to a method. and I get the values filled in that...
2
by: booksnore | last post by:
..eh I was stuck thinking up a subject title for this post for a while.. So I am processing a really big file (scary big). Each record is fixed length, I need to test conditions on certain fields...
5
by: Ian Meakin | last post by:
I am trying to consume a web service i have written. The web service returns to the client an array of objects. The web service when tested via inetrnet explorer retruns the correct xml data. I...
6
by: LordHog | last post by:
Hello all, I recently ran into a strange behavior which I don't understand. I have two 'Add' method which a slightly different signature which they look like public void Add( string varName,...
3
by: d d | last post by:
I have a large object with many sub-objects. They may go down 4 or 5 levels and I'm not sure how best to code a method that does operations on that data. Here's an attempt to make it an isolated...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
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,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.