Link to home
Start Free TrialLog in
Avatar of ErikVest
ErikVestFlag for Afghanistan

asked on

Creating an array within a class

Hi.

The layout of my program is as follow:
class Person
{
 public:

   string firstName;
   string lastName;
   int social_security_number;
 
void setPersondata(){
}

Void displayPersondata(){

};
int main()
Create a new object of the class Person

}

And here comes the question:
The plan is that i'm going to create a new object of the class Person and this object shall hold many numbers. I think that the best way is to store all of these numbers within an array.

How do i do that?
ASKER CERTIFIED SOLUTION
Avatar of lhl60
lhl60

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Infinity08
You can simply add an array of ints (or floats or whatever you need) to the object members.

Here's a tutorial on arrays :

        http://www.cplusplus.com/doc/tutorial/arrays.html


Btw, the main should probably be outside of the class.
Avatar of lhl60
lhl60

yes, a compile time defined array is the simplest thing to use,but you must at compile time know how big the array has to be.

like:

#define NUMBEROFNUMBERS 300

int numbers[NUMBEROFNUMBERS];

gives you space for NUMBEROFNUMBERS int's

you also have to keep track of how many elements in the array that is actually used, so you know where to put the next one.
if you don't know how many number you have to put in the array you need a dynamic container
Picking up on the point made by lhl60 on using a vector...

Unless you know in advance roughly how big your vector is likely to get (so you can presize it) or if you need to perform lots of inserts and deletes from the middle of the array, you might want to consider using a std::list instead. Growing a vector and inserting/deleting from the middle are very costly in terms of performance. A list does not incur this overhead. On the other hand, elements in a vector are accessed in constant time, where as the time to access a node in a list is dependent upon the size of the list since the nodes must be traversed. Also, a list uses a little more memory than a vector to store the pointers pointing to the next and previous node.

http://www.cplusplus.com/reference/stl/list/

The point is, the STL provides more than one type of container, each has good and bad points. Pick the correct container that suits your needs. The following link lists the most common STL containers and the time complexity for the most common operations on them all:

http://www.cplusplus.com/reference/stl/