Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert std::queue to std::vector

I need to make use of a queue of doubles because of the good properties it has as an ordered container. I want to pass this queue to a class constructor that accepts vectors. If I do that directly I get the following error:

candidate constructor not viable: no known conversion from 'std::queue' to 'std::vector &' for 2nd argument

How to cast a queue to a vector?

like image 461
Anthony Avatar asked Aug 01 '16 12:08

Anthony


People also ask

How do you make a vector queue?

vector<queue<int>> vec; // vector of queues vec. push_back(queue<int>()); // add a queue vec[0]. push(1); // push 1 into queue number 0.

How do you push a set element to a vector?

Create an empty vector and add set elements to it using for_each() and lambda function. Create an empty vector and then iterate over all elements in set and push them one by one into the vector. For iteration over all elements of set, use the for_each() algorithm and pass a lambda function as argument. // vector.

How do I store a vector in a queue?

The queue's constructor is as follows: explicit queue ( const Container& ctnr = Container() ); So you can have some vector v and construct a queue from it. vector<int> v; deque<int> d; /* some random magic code goes here */ queue<int, deque<int>> q(d(v));

Can you implement a queue with a vector?

You "can" use a vector over a queue, if the queue lifetime is short or if you know the maximum size of your queue. Just use a vector, push_back in it, and keep an index of where your "head" is.


1 Answers

The correct container to model both queue_like behaviour and vector-like behaviour is a std::deque.

This has the advantages of:

  1. constant-time insertion and deletion at either end of the deque

  2. ability to iterate elements without destroying the deque

std::deque supports the begin() and end() methods which means you can construct a vector (with compatible value-type) directly.

#include <vector>
#include <deque>

class AcceptsVectors
{
public:
  AcceptsVectors(std::vector<double> arg);
};

int main()
{
    std::deque<double> myqueue;

    auto av = AcceptsVectors({myqueue.begin(), myqueue.end()});
}

A non-mutating conversion of a queue to a vector is not possible.

like image 190
Richard Hodges Avatar answered Sep 27 '22 20:09

Richard Hodges