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

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

Candidate constructor is not viable: unknown conversion from 'std :: queue' to 'std :: vector &' for the second argument

How to pass a queue to a vector?

+4
source share
4 answers

The right container for modeling the behavior of both queue_like and vector behavior is std::deque.

This has the following advantages:

  • deque

  • deque

std::deque begin() end(), , ( ).

#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 queue vector .

+5

, . , .

std::vector<int> v;
while (!q.empty())
{
    v.push_back(q.front());
    q.pop();
}

, .

@David , ( , ). emplace_back() std::move() :

v.emplace_back(std::move(q.front()));
+4

std::vector , , , .

, std::queue:

template<typename T, typename Container=std::deque<T> >
class iterable_queue : public std::queue<T,Container>
{
public:
    typedef typename Container::const_iterator const_iterator;

    const_iterator begin() const { return this->c.begin(); }                                                                               
    const_iterator end() const { return this->c.end(); }
};

( , const, , .)

a vector:

#include <queue>
#include <vector>

using namespace std;

template<typename T, typename Container=std::deque<T> >
class iterable_queue : public std::queue<T,Container>
{
public:
    typedef typename Container::const_iterator const_iterator;

    const_iterator begin() const { return this->c.begin(); }                                                                               
    const_iterator end() const { return this->c.end(); }
};

int main() {
    iterable_queue<int> int_queue;
    for(int i=0; i<10; ++i)
        int_queue.push(i);

    vector<int> v(int_queue.begin(), int_queue.end());
    return 0;
}
+4

, std::queue std::vector. , .

std::queue- container adapter. The internal containerdefault is std::deque, but you can also set it to std::vector. The member element that holds this container is marked protectedfortunately. Therefore, you can crack it by subclassing queue.

Decision (!)

template<typename T>
struct my_queue : std::queue<T, std::vector<T>>
{
  using std::queue<T, std::vector<T>>::queue;
  // in G++, the variable name is `c`, but it may or may not differ
  std::vector<T>& to_vector () { return this->c; }
};

What is it!

Using

my_queue<int> q;
q.push(1);
q.push(2);
std::vector<int>& v = q.to_vector();

Demo .

+2
source

Source: https://habr.com/ru/post/1649785/


All Articles