I need to access a vector pointer elements, I have the following code for my animation structures (simplified here, unnecessary variables cut off):
struct framestruct {
int w,h;
};
struct animstruct {
vector<framestruct> *frames;
};
vector<framestruct> some_animation; // this will be initialized with some frames data elsewhere.
animstruct test; // in this struct we save the pointer to those frames.
void init_anim(){
test.frames = (vector<framestruct> *)&some_animation; // take pointer.
}
void test_anim(){
test.frames[0].w; // error C2039: 'w' : is not a member of 'std::vector<_Ty>'
}
The array works, I tested it by:
test.frames->size() and it was 7 as I planned.
So how can I access the vector elements (w and h) at N’th index from the vector?
You need to dererference the pointer before accessing the array. Just like you are doing with the
->operator to get the size.You could use the
->operator to also access the[]operator method, but the syntax isn’t as nice:If you want to be able to use
[]directly like a true vector syntactically, then you can either allow theframesmember to take a copy of thevector, you it can reference thevector. Or, you can overload[]on theanimstructitself to use the[]syntax on yourtestvariable.Copy:
Reference:
Overload: