Trader physics Trader physics - 1 year ago 86
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.


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:


for(int k = 0; k < N; ++k){

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

Answer Source

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)

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download