Reputation: 1524
I want to store queues in a queue structure from the stl
library. For some reasons I have to store a queue in each iteration of my program, but I think that create a new queue over and over again is too expensive.
I only know two ways to do this. The first one:
#include <iostream>
#include <deque>
using namespace std;
int main () {
unsigned int limit, i = 0;
deque<deque<int> > container;
cin >> limit;
for ( ; i < limit; i++ ) {
deque<int> values;
//set some values in the values structure.
setValues(values, i);
container.push(values);
}
}
the second one:
#include <iostream>
#include <deque>
using namespace std;
int main () {
unsigned int limit, i = 0;
deque<deque<int> > container;
deque<int> values;
cin >> limit;
for ( ; i < limit; i++ ) {
//reset the structure, i.e. delete al the previous values.
reset(values);
//set some values in the values structure.
setValues(values, i);
container.push(values);
}
}
the problem here is that I don't know any function for reset my queue, or maybe I have to do values=NULL
?
How can I do this in an efficient way?
Thanks! :D
Upvotes: 2
Views: 155
Reputation: 50036
You should check in debugger what your compiler is actually doing when you make copies of deque. I have checked in VS2013 and its all move semantics - as expected. This is a test code:
std::deque<int> getValues() {
std::deque<int> res;
res.push_back(1);
return res; // deque(_Myt&& _Right) called, also other compilers might use RVO
}
std::deque<int> ff;
std::deque<std::deque<int>> aff;
aff.push_back(getValues()); // void push_back(value_type&& _Val) called
at first it looks like a lot of copying, but actually in both problematic places move semantics are used, and only pointers of temporary objects are copied, so its all super fast.
But maybe you are stuct in pre c++11 world? At least this fragment
deque<deque<int> > container;
^^^
gives such a hint.
Upvotes: 2
Reputation: 206717
You can push an empty deque
in the loop, get a reference to it, and then add items to it.
#include <iostream>
#include <deque>
using namespace std;
int main () {
unsigned int limit, i = 0;
deque<deque<int> > container;
cin >> limit;
for ( ; i < limit; i++ ) {
container.push_back(deque<int>());
deque<int>& values = container.back();
//set some values in the values structure.
setValues(values, i); }
}
Upvotes: 2