structure initialization

Is it possible to use a variable in the creation of a structure? All of the texts I can find always use a constant ie

Struct Data
{
Int number;
}

Data Stuff; //this is where I want to be able to use a variable ie

Int set = count;

Data Stuff[set];//this definitely isn't right

Is anything like this even possible?
1
2
3
4
5
6
7
8
9
10
struct Data
{
    int number ;
};

int set = 7 ;

Data a = {set} ; // a.number == 7

Data b { set * 3 } ; // b.number == 21 C++11 
Sorry, looking back I can see i was far from clear in stating what I wanted to do, so let me try again.

I have this structure I am going to use.

struct Data
{
string division;
int Q1Sales;
int Q2Sales;
int Q3Sales;
int Q4Sales;

// Constructor
Data (string div = " ", int Q1 = 0, int Q2 = 0, int Q3 = 0, int Q4 = 0)
{
division = div;
Q1Sales = Q1;
Q2Sales = Q2;
Q3Sales = Q3;
Q4Sales = Q4;
}
};

What I want to do is have a way to create several instances ( an array) of this structure, either by a loop or other methods, without having to name each instance seperately. such as:

for (int count = 1; count <= 4; count ++ )
{
Data div[count](div, Q1, Q2, Q3, Q4);
}

But I know this wont work because the compiler wants a constant in the variable(count) location. I could do this, but then I would be limiting the number of possible instances which is what I am trying to avoid.

I hope this is a little clearer.
Last edited on
You have few choices.
1) An array. As you noted, you need to know the maximum number of occurrances in advance.
1
2
const int MAXDIV = 10;
Data salesdata[MAXDIV];


2) A vector
1
2
vector<Data>  salesdata;
salesdata.push_back (Data("div1",0,0,0,0));

A vector expands dynamically as you add data.

3) Youcould allocate the data on the heap dynamically once you know how many occurrances you need:
1
2
3
4
Data *salesdata; 
int numdiv;
cin >> numdiv;
salesdata = new Data[numdiv];


4) If the division names are unique, you could use a map.
1
2
3
std::map<string, Data> salesdata;
std::pair<"div1", Data("div1",0,0,0,0)> pr;
salesdata.insert (pr);

Like a vector, a map will expand dynamically, but has the added advantage that you can address the entries by the index (division).

PLEASE USE CODE TAGS (the <> formatting button) when posting code. It makes your code easier to read and it makes it easier to respond to your post.
Topic archived. No new replies allowed.