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?
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.
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.
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));
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.
The correct container to model both queue_like behaviour and vector-like behaviour is a std::deque
.
This has the advantages of:
constant-time insertion and deletion at either end of the deque
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With