向量的STL阵列内的类初始化 [英] Initialization of classes within an STL array of vectors
本文介绍了向量的STL阵列内的类初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有可能以一个单一的线。
I wanted to know if it is possible to initialize a bunch of classes within an array of vectors within a single "line".
class A {
public:
A(int k) {...}
};
[...]
#include <array>
#include <vector>
using namespace std;
array<vector<A>, 3> = { { A(5), A(6) }, { A(1), A(2), A(3) }, { } };
你可以想象这个解决方案不起作用(否则我就不会在这里!)。什么是做的最快方法?
As you can imagine this solution doesn't work (otherwise I wouldn't be here!). What is the fastest way to do it?
推荐答案
这做它,而不需要任何的反复提 A
:
This does it, without any need for repeated mentioning of A
:
array<std::vector<A>, 3> v{{ {1}, {2,3,4}, {} }};
如果构造了两个参数,你会花括号中它们写:
if the constructor took two arguments you would write them within braces:
array<std::vector<A2>, 3> v2{{ {{1,2}}, {{2,3},{4,5},{8,9}}, {} }};
我可能会preFER下面的语法也同样适用,如果构造函数是明确的。
I would probably prefer the following syntax which also also works if the constructor is explicit.
std::array<std::vector<A2>, 3> v2{{ {A2{1,2}}, {A2{2,3},A2{4,5},A2{8,9}}, {} }};
完整的示例:
#include <array>
#include <vector>
#include <iostream>
struct A2 {
A2(int k,int j) : mk(k),mj(j) {}
int mk;
int mj;
};
int main (){
std::array<std::vector<A2>, 3> v2{{ {{1,2}}, {{2,3},{4,5},{8,9}}, {} }};
int i=0;
for (auto &a : v2){
std::cout << "... " << i++ <<std::endl;
for (auto &b : a){
std::cout << b.mk << " " <<b.mj <<std::endl;
}
}
}
这篇关于向量的STL阵列内的类初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文