mjsxbo
mjsxbo

Reputation: 2266

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

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.

Upvotes: 3

Views: 1155

Answers (2)

Rostin
Rostin

Reputation: 161

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

Upvotes: 2

lubgr
lubgr

Reputation: 38267

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.

Upvotes: 2

Related Questions