简体   繁体   中英

How to convert std::queue<float> to float[]?

I know I could iteratively pop the elements into an array, but would prefer to directly cast it if possible.

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);

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM