Build a structure on each iteration

I want to store queues in a queue structure from a library stl

. For some reason, I have to keep a queue on every iteration of my program, but I think it is too expensive to create a new queue over and over again.

I only know two ways to do this. The first:

#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);
    }
}

      

second:

#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 is i dont know of any function to reset my queue, or maybe i need to do values=NULL

?

How can I do this in an efficient way?

Thank you !: D

+3


source to share


2 answers


You can click an empty deque

in a loop, get a link 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);    }
}

      

+2


source


You should check in the debugger what your compiler is doing when you make copies of the deque. I checked in VS2013 and all move semantics - as expected. This is the 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 in fact, both problem areas use move semantics, and only temporary object pointers are copied, so it's all very fast.



But maybe you are in a pre C ++ 11 world? At least this snippet

  deque<deque<int> > container; 
                 ^^^

      

gives such a hint.

+2


source







All Articles