无论如何都要避免做这样的事情:
std::queue<myStruct> part1, part2, part3, part4, part5, part6, part7, part8, part9, part10;
void setup(){
myVector.push_back(part1);
myVector.push_back(part2);
myVector.push_back(part3);
myVector.push_back(part4);
myVector.push_back(part5);
myVector.push_back(part6);
myVector.push_back(part7);
myVector.push_back(part8);
myVector.push_back(part9);
myVector.push_back(part10);
}
虽然这只能达到第10部分,但我可能会达到50或更高。它只是编码的一部分,它必须在某个地方声明,或者是否有动态的方式我可以声明并将这些队列分配给myVector,而不用这样写它?
TIA
答案 0 :(得分:8)
一个简单的方法:
std::vector<std::queue<myStruct>> myVector(10);
完成!
答案 1 :(得分:0)
假设你的结构看起来像这样:
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