0

I want to create an array of structures. The structure uses a constructor as shown below:

struct struct_seedinfo {
    struct_seedinfo(const mxArray *prhs[ ],const int seed_id){  
        mxArray *mat_coords, *mat_defvectorinit, *mat_corrcoef, *mat_roi_id;

        mat_coords = mxGetField(prhs[1],seed_id,"coords");
        coords = mxGetPr(mat_coords);

        mat_defvectorinit = mxGetField(prhs[1],seed_id,"defvectorinit");
        defvectorinit = mxGetPr(mat_defvectorinit);

        mat_corrcoef = mxGetField(prhs[1],seed_id,"corrcoef");
        corrcoef = *(mxGetPr(mat_corrcoef));

        mat_roi_id = mxGetField(prhs[1],seed_id,"roi_id");
        roi_id = *(mxGetPr(mat_roi_id));
    }
    double *coords;
    double *defvectorinit;
    double corrcoef;
    double roi_id;
    static int num_seeds;
};

How could I create an arbitrary sized array of this structure? I need to allocate memory for it, but it seems like I would need to allocate memory without calling the constructor, and then call the constructor later in a forloop. Is there a good or preferred way of doing this? Thanks.

JustinBlaber
  • 4,629
  • 2
  • 36
  • 57
  • Dow you know your array size in runtime or does it keep changing? – oopsi Sep 14 '12 at 17:31
  • The array size is only known after the function is called but stays constant throughout the function. I may try the vector route even though it stays constant just to learn more about STL. – JustinBlaber Sep 14 '12 at 17:38

2 Answers2

2

You can do std::vector<struct_seedinfo>. This will create an array and it will automagically increase in size when needed.

You'll also need to overload the copy constructor and copy-assignment operator for your struct to be able to be used in a vector. You need a destructor too. This is called the Rule of Three in C++

Community
  • 1
  • 1
Tony The Lion
  • 61,704
  • 67
  • 242
  • 415
1

Well since the size stay constant, you can use the following solution : *This assumes your ok with defining a default constructor.

First declare a default constructor in your class.

struct_seedinfo(){
//If you want to initlaize something.
}

Than you can use the following to create you array :

 struct_seedinfo * arr = new struct_seedinfo[size_of_array];

And then you need for each space to do your specific build :

arr[i] = struct_seedinfo(//arguments);

This is if you badly need an array, i do also think the vector solution is better.

oopsi
  • 1,919
  • 3
  • 21
  • 28
  • I'll try out the vector route. If it takes too long or I end up not liking it, I'll revert to this. But yea, this is what I was initially looking for. Thanks! – JustinBlaber Sep 14 '12 at 17:52