简体   繁体   English

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

[英]How initialize a vector of objects in C++11

Given the following class: 鉴于以下课程:

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

What's the easiest way to initialize my vector: std::vector<MyRecord> myVector with some data? 初始化vector的最简单方法是什么: std::vector<MyRecord> myVector包含一些数据?

Demonstrated via example: 通过示例演示:

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

For verification, the following code 要进行验证,请使用以下代码

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

will output: 将输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM