Tito
Tito

Reputation: 2300

Cast/Convert const vector<uint8_t> to const vector<char> in c++

What would be the most performant way to convert/cast const vector<uint8_t> to const vector<char> in c++?

Upvotes: 0

Views: 1308

Answers (1)

Marshall Clow
Marshall Clow

Reputation: 16690

This should work (untested code):

std::vector<uint8_t> v1 = // something;
const char *p = (const char *) v1.data();
std::vector<char> v2(p, p + v1.size());

Now you have two vectors; one of uint8_ts and one of chars

One memory allocation, one call to memcpy.

[Later: @Tito pointed out that vector doesn't have a (pointer, size) constructor (like string/span/string_view) Rewrote the example code to use the (iterator, iterator) constructor instead]

Upvotes: 2

Related Questions