473,654 Members | 3,253 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.toS tring();

rather than:

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

Jun 1 '06 #1
4 1677
On 2006-06-01 12:52, Cl*******@hotma il.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.toS tring();

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*******@hotma il.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.toS tring();

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*******@hotma il.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.toS tring();

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<Par ticle>& pv)
{
std::copy(pv.be gin(), pv.end(), std::ostream_it erator<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(myPar ticles,
myParticles + n,
std::ostream_it erator<Particle >(std::cout, "\n"));
std::cout << "\nVector:\ n";
std::vector<Par ticle> myParticles2(3) ;
std::copy(myPar ticles2.begin() ,
myParticles2.en d(),
std::ostream_it erator<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******@gehen nom.invalid> wrote:
int main()
{
int n = 3;
Particle* myParticles = new Particle[n];
// better would be std::vector

std::cout << "Array:\n";
std::copy(myPar ticles,
myParticles + n,
std::ostream_it erator<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<Par ticle> myParticles2(3) ;
std::copy(myPar ticles2.begin() ,
myParticles2.en d(),
std::ostream_it erator<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
1478
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 numarray. I intend to treat the function as a variable, so ufuncs are probably not appropriate-- I
3
2075
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 would also appreciate any general criticism you have to offer. I don't know yet how to write the degradation-path code for browsers that don't support the DOM methods I'm using, so there are some commented-out paths below. If the content...
6
22513
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 instance (in this case 'myDog'). Of course it would be better if I could somehow know from within write() that the name of the object instance was 'myDog' without having to pass it as a parameter. //////////////////////////////// function...
2
1924
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 method. I can debug the method and values are being assigned. But when I am in the calling procedure I no longer see the values, I
2
1555
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 in the record. At the moment the most efficient way I've found to process the data is a series of nested if/else statements so like below. My question is does anyone know of a better way to process this kind of logic. I can't use a switch...
5
2186
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 just dont understand how in my client application to read the xml returned back. How do i capture the xml stream and then read it to use on the client? -------------------------------- Copy of some xml outputted by the web service when...
6
2006
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, ScriptVarType type, object value ) public void Add( string varName, ScriptVarType type, object values )
3
1492
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 example: var level1={ info:"abc", //lots of other properties here alongside info level2:{ moreinfo:"def", //lots of properties at this level too level3: //various other level 3 objects },
0
8379
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8816
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8709
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8494
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
4150
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4297
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2719
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1924
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1597
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.