简体   繁体   中英

C++ vector change type

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.

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.

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

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