[英]Initializer list for vector of objects
I have the following sample code. 我有以下示例代码。 Is it possible to initialize a list of objects without specifying the "Test" in the vector of objects, or is this the best way?
是否可以在不指定对象向量中指定“测试”的情况下初始化对象列表,还是最好的方法? Thanks.
谢谢。
class Test {
public:
Test(const std::initializer_list<int> list) : m_(list) {
}
private:
std::vector<int> m_;
};
int main(int argc, char **argv) {
std::vector<Test> v = { Test({1, 2, 3}), Test({1, 2, 4}) };
}
The following works: 以下作品:
std::vector<Test> v = {{1, 2, 3}, {1, 2, 4}};
But I'm not sure if this is what you meant. 但是我不确定这是否是您的意思。
The following are all valid methods to initialize a vector<Test>
. 以下是初始化
vector<Test>
所有有效方法。
std::vector<Test> v1 = { Test({1, 2, 3}), Test({1, 2, 4}) };
std::vector<Test> v2{Test({1, 2, 3}), Test({1, 2, 4}) };
std::vector<Test> v3 = { {1, 2, 3}, {1, 2, 4}};
std::vector<Test> v4{{1, 2, 3}, {1, 2, 4}};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.