E.g given vector<uint8>
of length 100, how to create new vector<uint16>
of 50 elements. Preferably without copying?
(Edit: info from my comments)
To illustrate:
I have a uint16 grayscale image file, my 3rd party lib returns a vector of uint8. Every 2 bytes = 1 pixel. It is practical for me to work with a vector of uint16. I think the only difference between this vector<uint8>
and a corresponding vector<uint16>
is that the bytes are read in a "concatenated" manner (i.e. chunks of 2 bytes = 1 value).
I could loop and combine every 2 elements into a new vector element, but that seems inefficient, since the memory layout is the same. I was hoping I could combine some cast and maybe a move constructor to create a vector<uint16>
--without copying the original vector<uint8>
bytes again.
Edit 2: To dispel any possible misunderstandings I drew a picture, forgive my poor ascii art :)
container of uint8 values in memory:
[ _ ] | [ _ ] | [ _ ] | [ _ ] ...
|^^|
accessing element = accessing 1 byte
container of uint16 values in memory is also just a sequence of bytes;
[ _ ] | [ _ ] | [ _ ] | [ _ ] ...
|^ ^ ^ ^ ^|
accessing element = accessing 2 bytes (lets say my system read this as big-endian)
I already have the sequence of bytes in vector v1. I just want a v2 of different type so I can access them differently. If it turns out the uint16 values are read as little-endian I could still work with that.
Edit 3: So far it seems the answer by black is the best to my understanding (I will accept later if nothing changes), it still seems odd that there is no simple or STL solution to this. Though thanks to everyone for their prompt input and patience with my attempts at explaining myself.