如何初始化包含向量作为成员的结构向量?

时间:2010-12-09 22:42:42

标签: c++ stl

我正在使用Boost :: assign来初始化结构向量,如下所示:

const std::vector<spriteInfo> Resources::hudObjectInfo = boost::assign::list_of
    ( spriteInfo(FALSE, SCORE_START_X, SCORE_START_Y, CENTER_ALIGN ))
    ( spriteInfo(FALSE, SCORE_START_X+NUM_DIFF, SCORE_START_Y, CENTER_ALIGN))
    ... /* and so on */
;

NB。 spriteInfo结构当前看起来像这样:

struct spriteInfo
{
    spriteInfo::spriteInfo(bool i, float x, float y, int align):
        invisible(i), x1(x), y1(y), alignment(align){}
    bool        invisible;
    float       x1;
    float       y1;
    int         alignment;
};

但是,我想将std::vector<int>作为spriteInfo的成员。

如果我这样做,上面的作业怎么样?即,您可以初始化向量,同时将其作为参数传递给构造函数吗?

1 个答案:

答案 0 :(得分:3)

这应该做:

struct spriteInfo
{
    spriteInfo(bool i, float x, float y, int align, const std::vector<int> &v):
        invisible(i), x1(x), y1(y), alignment(align), something(v) {}
    bool             invisible;
    float            x1;
    float            y1;
    int              alignment;
    std::vector<int> something;
};

int main()
{
    const std::vector<spriteInfo> Resources::hudObjectInfo = boost::assign::list_of
        ( spriteInfo(FALSE, SCORE_START_X, SCORE_START_Y, CENTER_ALIGN, boost::assign::list_of(1)(2)(3)))
        ( spriteInfo(FALSE, SCORE_START_X+NUM_DIFF, SCORE_START_Y, CENTER_ALIGN, boost::assign::list_of(4)(5)(6)))
    ;
}