Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing vector of structures

Tags:

c++

struct

vector

I have a problem with accessing vector of structures in another structure. There might be something I cannot se ...

Lets have structure like this:

struct Struct_1 {
  int Id;
  int Mode;
  string Name;
};

Another structure like this:

struct Record {
  int Id;
  int StructId;
  string Name;
  vector<Struct_1> structHolder;
};

Now I need to fill some structures Record

int recordCount = 10;
vector<Record> recordVector(recordCount);
for(int i = 0; i < recordVector.size(); ++i){
   recordVector[i].Id = ...
   recordVector[i].StructId = ...
   recordVector[i].Name = ...
   // till now it is ok 
   recordVector[i].structHolder[i].Id = ..
   recordVector[i].structHolder[i].Mode = ..
   // and here it fails when i access vector

}

When I am trying to fill the data of structHolder, it fails with "C++ vector subscript out of range" Does anybody know where is a problem? Thank you a lot!

like image 843
AxelF93 Avatar asked Dec 31 '22 23:12

AxelF93


1 Answers

recordVector[i].structHolder is an empty std::vector. So you cannot access any item of it.

One solution is to fill an instance of Struct_1 an push_back to your vector

Struct_1 myStruct;
myStruct.Id = 1
recordVector[i].structHolder.push_back(myStruct);
like image 164
Hubi Avatar answered Jan 03 '23 11:01

Hubi