2

我需要访问一个矢量指针元素,我的动画结构有以下代码(这里简化,不必要的变量被切断):

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>'
}

该阵列有效,我通过以下方式对其进行了测试: test.frames->size()它是我计划的 7。

那么如何从向量中访问第 N 个索引处的向量元素(w 和 h)?

4

2 回答 2

5

您需要在访问数组之前取消引用指针。就像您与->操作员一起获取尺寸一样。

(*test.frames)[0].w;

您也可以使用->运算符来访问[]运算符方法,但语法不是很好:

test.frames->operator[](0).w;

如果您希望能够在[]语法上像真正的向量一样直接使用,那么您可以允许frames成员获取 的副本vector,您可以引用vector. 或者,您可以重载自身以使用变量[]的语法。animstruct[]test

复制:

struct animstruct { vector<framestruct> frames; };
animstruct test;
void init_anim(){ test.frames = some_animation; }

test.frames[0].w;

参考:

struct animstruct { vector<framestruct> &frames;
                    animstruct (vector<framestruct> &f) : frames(f) {} };
animstruct test(some_animation);
void init_anim(){}

test.frames[0].w;

超载:

struct animstruct { vector<framestruct> *frames;
                    framestruct & operator[] (int i) { return (*frames)[i]; } };
animstruct test;
void init_anim(){ test.frames = &some_animation; }

test[0].w;
于 2012-07-20T22:04:45.530 回答
1

test.frames指向一个向量,所以你需要在索引到向量之前取消引用它。

(*test.frames)[0].w
于 2012-07-20T22:05:48.363 回答