Trader physics Trader physics - 2 months ago 7
C++ Question

c++ right way to initialize a vector of a struct

i searched a lot here, but there is no right explanation for me, for an advanced newbie in c++. I worked before with vector of structs and now I get segmentation faults...

Thats why I want to know how such objects actually works and if it is the right the way I am doing!

I have a struct like

struct numberOfSpecies {
int predator;
int prey1;
int prey2;
};


and a vector of it:

std::vector<numberOfSpecies> size;


Before I resize it and fill it with values.

size.resize(100);


what is actually this doing? Is this right for a struct?
It looks like it is initialized with zeros...

Now I am doing this like:

size[t].predator=0;
size[t].prey1=0;
size[t].prey2=0;

for(int k = 0; k < N; ++k){
size[t].predator++;
size[t].prey1++;
size[t].prey2++;
}


Is this right? Where are possible issues? How to do it better?

Answer

The easiest and 'correct' solution here is probably to just use the resize() function that belongs to the vector object with aggregate initialization (if you have access to c++11 and on), something like

size.resize(100,{0,0,0}); //aggregate initialization 

for(int k = 0; k < N; ++k)
{
    size[t].predator++;
    size[t].prey1++;
    size[t].prey2++;
}

All members of each numberOfSpecies object will be initialized to 0.