user2881553
user2881553

Reputation:

Expression: vector subscript out of range C++?

I am trying to access a variable, and print it out. However, I encounter the Vector subscript out of range error.

I am doing

cout << myStruct->myVector[0].GetCoordinate(0) << endl;

where myStruct points to a structure that contains a vector myVector of points. So I am trying to print out its first coordinate.


To debug:

cout << typeid(myStruct->myVector[0].GetCoordinate(0)).name() << endl;

gives me

float

and

cout << sizeof(myStruct->myVector[0].GetCoordinate(0)) << endl;

gives me

4

However, when I directly print its value

cout << myStruct->myVector[0].GetCoordinate(0) << endl;

Error message:

enter image description here

Upvotes: 1

Views: 2432

Answers (2)

MenschMeier
MenschMeier

Reputation: 17

Issue caused by:

tlen = __byte_encode_array(buf, offset + pos, maxlen - pos, &this->data[0], this->size);

Impossible to access a non-existing element in a vector.

Upvotes: 1

Zeta
Zeta

Reputation: 105905

Your vector is empty. Any index that's not between 0 and .size() (excluding the latter) is out of range. Since there is no index between 0 and 0, every index is out of range.

You need to populate your vector first, e.g. use .resize or .push_back.

Upvotes: 4

Related Questions