I know I could iteratively pop the elements into an array, but would prefer to directly cast it if possible.
CodePudding user response:
It is not possible to "cast" a std::queue
or std::deque
to a vector or an array.
You can however copy the content of a double ended queue into another container:
deque<int> d{1,2,3,4};
vector<int> v(d.size());
copy(d.cbegin(),d.cend(), v.begin());
for (auto i:v) cout<< i<<endl;
The same for a built-in array, provided you have allocated one of sufficient size:
int a[4]; // or dynamic allocation, but vector is more convenient then.
copy(d.cbegin(),d.cend(), a);
CodePudding user response:
Quick answer, you can't cast a queue
to an array. Even if you expose the underlying container, it would likely be a deque
or list
, which cannot be cast to an array since the data are not stored contiguously.
The straightforward way is to just read/pop each element, and push them to another vector
.
However, you can also inherit from a queue
and expose the underlying container:
template<typename T>
class exposed_queue : public std::queue<T>
{
public:
using std::queue<T>::c;
};
Now you are able to access the underlying container, and have a easy way to fill a vector
:
std::queue<float> q {{1,2,3,4,5}};
exposed_queue<float> eq(q);
std::vector<float> v(eq.c.begin(), eq.c.end());