【问题标题】:How to read element from a vector pointer?如何从向量指针中读取元素?
【发布时间】:2012-07-20 22:02:23
【问题描述】:

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

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-&gt;size() 和我计划的一样是 7 点。

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

【问题讨论】:

  • 另外,你不需要在这里使用 C 风格的转换。写test.frames = &amp;some_animation;
  • @qehgt,啊,我在想我做错了什么/矫枉过正。
  • 如果有构造函数,为什么会有init_anim?编写没有太多花里胡哨的纯 C++ 代码通常很好,但这似乎有点过头了。
  • @pmr,我只是让代码尽可能简单。 -> 别担心,我确实使用构造函数!

标签: c++ visual-c++ vector c++03


【解决方案1】:

您需要在访问数组之前取消引用指针。就像您使用 -&gt; 运算符获取大小一样。

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

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

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;

【讨论】:

  • 嗯,[] 操作符的绝妙技巧。无论如何有可能使这种访问看起来完全像没有指针吗?喜欢test.frames[0].w
  • @Rookie:因为test.frames 是一个指针,你必须取消引用它才能获得它所指向的vector 对象。如果您想避免额外取消引用的语法,您可以将对象更改为使用引用。我会更新答案。
  • 看起来很复杂,我稍后再看,现在我只是使用一个宏:#define getframe (*test.frames):P
【解决方案2】:

test.frames 指向一个向量,因此您需要在索引到向量之前取消对它的引用。

(*test.frames)[0].w

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 2013-05-08
    • 1970-01-01
    • 2015-12-06
    相关资源
    最近更新 更多