如何在C ++ 11中初始化对象向量

时间:2013-03-13 15:45:18

标签: c++ c++11 stdvector

鉴于以下课程:

class MyRecord {
public:
    int a;
    int b;
    MyRecord() : MyRecord(8, 9) {};
    MyRecord(int a, int b) : a(a), b(b) {};
};

初始化矢量的最简单方法是什么: std::vector<MyRecord> myVector有一些数据吗?

1 个答案:

答案 0 :(得分:2)

通过示例演示:

MyRecord exampleRecord(3,4);
std::vector<MyRecord> myVector = {{1,2}, {}, exampleRecord};

要进行验证,请使用以下代码

for (MyRecord &record : myVector) {
    std::cout << "a:" << record.a << " b:" << record.b << std::endl;
}

将输出:

a:1 b:2
a:8 b:9
a:3 b:4