alfa_80
alfa_80

Reputation: 427

Creating unknown number of multiple C++ objects automatically

I would like to know C++ way of creating multiple indefinite number of objects (0..n) automatically. The use case is as below:

Let say I have a script that a user has to enter related data (width, length, height) that later on Box class will contain those data.

Box
{ 
    ...
    ...
    double width;
    double length;
    double height;
    ...
    ...
}

The script looks like:

<id="width" value="1"/>
<id="length" value="3"/>
<id="height" value="3"/>

<id="width2" value="3"/>
<id="length2" value="3"/>
<id="height2" value="4"/>

<id="width3" value="2"/>
<id="length3" value="3"/>
<id="height3" value="3"/>

In other words, how can I instantiate those object which number of the objects is not known in advance, rather, it depends on how many box information (width and so on) is entered by the user.

Also, is there any design pattern for that?

Upvotes: 2

Views: 4321

Answers (4)

Raydel Miranda
Raydel Miranda

Reputation: 14360

The obvious is that in first place you have to parse the xml file. All other answers assumes you already know how to do that. Here I will complement QuinnFTW's answer and also give you a link to Parsing xml with Boost. Why? Well, if you knew how to obtain a list of objects from the xml, you were not asking this question.

And, complementing QuinnFTW's answer a code sample using std::vector.

#include <vector>
#include <iostream>

using namespace std;

struct Box { 
    double with, length, height; 
    Box():with(0), length(0), height(0) {}
};

typedef std::vector<Box> box_list_t;


int main()
{

    Box a, b, c;
    // Create the vector.
    box_list_t box_list;

    box_list.push_back(a);  // Add a to the vector;
    box_list.push_back(b);  // Add b to the vector;
    box_list.push_back(c);  // Add c to the vector;

    box_list[0].with = 0;   // Change the with of a to 0;
    cout << box_list[1].with << endl; // Prints b.with. Have not been initialized.


    return 0;
}

Upvotes: 1

QuinnFTW
QuinnFTW

Reputation: 554

Use std::vector

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

It will allow to add an unknown number of objects to it, and works like an array

Upvotes: 6

frogatto
frogatto

Reputation: 29285

Suppose you want n objects type Box

Box **array = new Box*[n];
for(int i = 0; i < n; i += 1) {
    array[i] = new Box();
}

UPDATE #1

if you want a variable length list, you can try:

Upvotes: 3

Wojtek Surowka
Wojtek Surowka

Reputation: 20993

You cannot during runtime add new members to your class based on XML. The best you can do is to you std::map in your class, which will map the ids to values. Something like

class Box
{
  std::map<std::string, int> values;
...

and then e.g. in Box constructor

values["width"] = 1;
values["width2] = 3;

Obviously instead of hard coding it you may read the values from XML and add them.

Upvotes: 2

Related Questions