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.
(*test.frames)[0].w;
You could use the -> operator to also access the [] operator method, but the syntax isn't as nice:
test.frames->operator[](0).w;
If you want to be able to use [] directly like a true vector syntactically, then you can either allow the frames member to take a copy of the vector, you it can reference the vector. Or, you can overload [] on the animstruct itself to use the [] syntax on your test variable.
Copy:
struct animstruct { vector<framestruct> frames; };
animstruct test;
void init_anim(){ test.frames = some_animation; }
test.frames[0].w;
Reference:
struct animstruct { vector<framestruct> &frames;
animstruct (vector<framestruct> &f) : frames(f) {} };
animstruct test(some_animation);
void init_anim(){}
test.frames[0].w;
Overload:
struct animstruct { vector<framestruct> *frames;
framestruct & operator[] (int i) { return (*frames)[i]; } };
animstruct test;
void init_anim(){ test.frames = &some_animation; }
test[0].w;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With