假设您的结构如下所示:
struct myStruct{
//random variables that your struct may contain
int num;
std::string str;
char ch;
//Default Constructor
//This allows your to create your structs without specifying any values;
myStruct():
num{999},str{"default"},ch{'z'}{}
//Parameterized Constructor
//This allows you to create your structs with specified values during initialization
myStruct(int const numIn, std::string const& strIn, char const chIn):
num{numIn},str{strIn},ch{chIn}{}
};
这将允许您通过以下方式创建实例:
//calling default constructor
myStruct part1, part2, part3;
//calling parameterized constructor
myStruct part4{4,"4",'4'}, part5{5,"5",'5'}, part6{6,"6",'6'};
现在您想将每个容器放入一个容器中,然后将这些容器放入另一个容器中?
//this is a vector holding one deque holding 6 structs
vector<deque<myStruct>> vec{{part1,part2,part3,part4,part5,part6}};
+-------+
| vec |
| |
| [0] |
+-------+
|
\'/
+-------+
| deq |
| |-> part1
| [0] |
+-------+
| deq |
| |-> part2
| [1] |
+-------+
| deq |
| |-> part3
| [2] |
+-------+
| deq |
| |-> part4
| [3] |
+-------+
| deq |
| |-> part5
| [4] |
+-------+
| deq |
| |-> part6
| [5] |
+-------+
//this is a vector holding 6 deques each holding 1 struct
vector<deque<myStruct>> vec2{{part1},{part2},{part3},{part4},{part5},{part6}};
+-------++-------++-------++-------++-------++-------+
| vec || vec || vec || vec || vec || vec |
| || || || || || |
| [0] || [1] || [2] || [3] || [4] || [5] |
+-------++-------++-------++-------++-------++-------+
| | | | | |
\'/ \'/ \'/ \'/ \'/ \'/
+-------++-------++-------++-------++-------++-------+
| deq || deq || deq || deq || deq || deq |
| || || || || || |
| [0] || [0] || [0] || [0] || [0] || [0] |
+-------++-------++-------++-------++-------++-------+
| | | | | |
\'/ \'/ \'/ \'/ \'/ \'/
part1 part2 part3 part4 part5 part6
不过,我们可以做得更好。让我们初始化您的结构,同时将它们推入双端队列,同时将双端队列推入向量。
//this is a vector holding one deque holding 6 structs
vector<deque<myStruct>> vec{{{1,"1",'1'},{2,"2",'2'},{3,"3",'3'},{4,"4",'4'},{5,"5",'5'},{6,"6",'6'}}};
//this is a vector holding 6 deques each holding 1 struct
vector<deque<myStruct>> vec2{{{1,"1",'1'}},{{2,"2",'2'}},{{3,"3",'3'}},{{4,"4",'4'}},{{5,"5",'5'}},{{6,"6",'6'}}};
但请记住,这是所有 C++11 初始化功能。我建议你阅读这篇文章来习惯。
http://www.informit.com/articles/article.aspx?p=1852519
要编译这样的代码,请确保您的编译器是最新的并且您拥有适当的库文件。如果您使用 gcc,请使用以下标志进行编译:
g++ -std=c++0x -o main main.cpp