0

I'm wondering if the below is a valid conversion of vector type:

vector<UINT16> u;
vector<UINT8> v(u.begin(), u.end());

I found this link relevant: C++ convert vector<int> to vector<double>

However, need to confirm if the above conversion is valid or not.

Community
  • 1
  • 1
pree
  • 2,297
  • 6
  • 37
  • 55

2 Answers2

3

The std::vector range constructor specifically says:

(3) range constructor Constructs a container with as many elements as the range [first,last), with each element constructed from its corresponding element in that range, in the same order.

This means that if your UINT16 vector u has 10 elements, v will have 10 elements too. Not caring about any overflow it may cause. If by 'valid' you mean that it will magically split up uint16 values into 2 uint8's and add them to v then no, that's not the case.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
1

From the Windows.h header:

typedef unsigned char       UINT8, *PUINT8;
typedef unsigned short      UINT16, *PUINT16;

Char and Short can both be used as numbers.

They both have an implicit conversion between themselves.

Yes, it is valid. (Is it safe is another question entirely)

However, previous numeric "limits" will be lost, as due to the nature of vectors these will be allocated to fit the "fitting" vector. This may cause issues depending on the value of the UINT16's

DarmaniLink
  • 126
  • 10
  • 1
    I am curious why you say *(Is it safe is another question entirely)*. Do you feel this is unsafe? – NathanOliver May 04 '16 at 21:29
  • This more of a general answer, not so much 100% applying to this. Since several examples are shortened, they're rarely the original thing. If you're using pointers, this has a chance at being unsafe (due to different sizes). – DarmaniLink May 04 '16 at 21:34