Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push vectors into queue<vector<int>> using loop?

Tags:

c++

stl

vector

I want to push vectors into my queue using the following code:

queue<vector<int>> q;

for(int i=0;i<10;i++) {
    vector<int> t(3,-1);
    q.push(t);
}

vector<int> p = q.front();
q.pop();

Is this correct? I'm worried that since t is only defined inside the loop it will get destroyed as soon the loop is over. So will the pushed vectors still exist in the queue after the loop is over?

I had a similar code which was giving segmentation fault, so I thought this might be the problem.

like image 840
Nirvan Anjirbag Avatar asked Jul 05 '26 14:07

Nirvan Anjirbag


2 Answers

Is this correct?

Yes. When used with the default std::deque backend, std::queue::push(const T&) copies its argument into the underlying container through its internal std::deque instance. When the argument goes out of scope, that's fine, q owns its own copy of it.

Note, however, that

q.push(std::move(t));

would be more efficient, as this requires only move-constructing a vector instance, which is cheaper. This is again safe as you don't use t after moving it to the queue.

like image 146
lubgr Avatar answered Jul 07 '26 04:07

lubgr


As @lubgr mentioned in his answer this is correct, the container will have a copy of the argument when using std::queue::push

Using std::queue::emplace is more efficient as it pushes a new element into the container so no temporary is created and no copy/move operation would occur

You tagged this question with C++14 standard, std::queue::emplace is available since C++11

https://en.cppreference.com/w/cpp/container/queue/emplace

like image 22
Rostin Avatar answered Jul 07 '26 03:07

Rostin