AxelF93
AxelF93

Reputation: 43

Accessing vector of structures

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!

Upvotes: 4

Views: 259

Answers (3)

Hubi
Hubi

Reputation: 1629

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);

Upvotes: 5

Blaze
Blaze

Reputation: 16876

You need to fill the vector before you can access it. You can do it with resize, for instance:

vector<Record> recordVector(10);
int main() {
    for (int i = 0; i < recordVector.size(); ++i) {
        recordVector[i].structHolder.resize(5);
        for (int j = 0; j < recordVector[i].structHolder.size(); j++) {
            recordVector[i].structHolder[j].Id = j;
            recordVector[i].structHolder[j].Mode = 1;
        }
    }
}

In this example every recordVector gets five Struct_1 in its structHolder and we fill them with a nested loop.

Upvotes: 2

lubgr
lubgr

Reputation: 38267

Indexing into a nested std::vector accesses only existing elements in that vector. It can't add a new one. You need to initialize the data member structHolder, too, e.g.

for(int i = 0; i recordVector.size(); ++i){
   // as before...
   recordVector[i].structHolder.resize(42);

   // Now you can access the 42 Struct_1 instances via indexing:

   rectorVector[i].structHolder[0].Id = 10;
   // ...
}

Upvotes: 2

Related Questions