寻找一种重新初始化结构的简单方法

时间:2011-07-13 20:08:02

标签: c++ struct initialization

我有一个名为CoolStruct的结构:

struct CoolStruct

{
    int id;
    uint32 type;
    uint32 subtype;
    String name;
};

我也有这些结构的载体:

std::vector<CoolStruct> coolVector;

我想创建一组结构,这些结构具有push_back到此coolVector的预定义值。我想让代码变得笨拙和丑陋。我真的想保留这种表示法:

CoolStruct t = {1, EQData::EQ_EFFECT_TYPE_PARAMETRIC, 0, T("Parametric")};
coolVector.push_back(t);
CoolStruct t =  {2, EQData::EQ_EFFECT_TYPE_FILTER_LOW_PASS,EQData::EQ_FILTER_TYPE_FILTER_BUTTERWORTH_12DB, T("Low Pass")};
coolVector.push_back(t);

但当然这不起作用......不允许重新初始化。有没有其他解决方案可以让它尽可能可读?我能想到的唯一选择是手动设置结构的每个参数:

t.id = whatever; t.type = somethingelse; t.subtype = thisisalotofcode; t.name = justtosetupthisvector;
coolVector.push_back(t);

2 个答案:

答案 0 :(得分:3)

怎么样:

CoolStruct t1 = {1, EQData::EQ_EFFECT_TYPE_PARAMETRIC, 0, T("Parametric")};
coolVector.push_back(t1);
CoolStruct t2 = {2, EQData::EQ_EFFECT_TYPE_FILTER_LOW_PASS,EQData::EQ_FILTER_TYPE_FILTER_BUTTERWORTH_12DB, T("Low Pass")};
coolVector.push_back(t2);

在C ++ 0x中,我认为你应该可以这样做:

CoolStruct t;
t = {1, EQData::EQ_EFFECT_TYPE_PARAMETRIC, 0, T("Parametric")};
coolVector.push_back(t);
t = {2, EQData::EQ_EFFECT_TYPE_FILTER_LOW_PASS,EQData::EQ_FILTER_TYPE_FILTER_BUTTERWORTH_12DB, T("Low Pass")};
coolVector.push_back(t);

甚至:

coolVector.push_back({1, EQData::EQ_EFFECT_TYPE_PARAMETRIC, 0, T("Parametric")});
coolVector.push_back({2, EQData::EQ_EFFECT_TYPE_FILTER_LOW_PASS,EQData::EQ_FILTER_TYPE_FILTER_BUTTERWORTH_12DB, T("Low Pass")});

事实上,如果你真的想要获得创意(并且你没有任何你想要保留的元素),你可以用这种语法替换整个向量:

coolVector = {
   {1, EQData::EQ_EFFECT_TYPE_PARAMETRIC, 0, T("Parametric")},
   {2, EQData::EQ_EFFECT_TYPE_FILTER_LOW_PASS,EQData::EQ_FILTER_TYPE_FILTER_BUTTERWORTH_12DB, T("Low Pass")}
};

答案 1 :(得分:1)

如果你添加一个简单的构造函数:

struct CoolStruct
{
    CoolStruct(int id, uint32 type, uint32 subtype, String name) : id(id), type(type), subtype(subtype), name(name) {}
    int id;
    uint32 type;
    uint32 subtype;
    String name;
};

然后你可以这样做:

CoolVector.push_back(CoolStruct(1, EQData::EQ_EFFECT_TYPE_PARAMETRIC, 0, T("Parametric")));
CoolVector.push_back(CoolStruct(2, EQData::EQ_EFFECT_TYPE_FILTER_LOW_PASS,EQData::EQ_FILTER_TYPE_FILTER_BUTTERWORTH_12DB, T("Low Pass")));