Convert std::vector<uint8_t> to std::string_view

Viewed 1900

I have some data of type std::vector<uint8_t>. I would like to interpret it as a string and do some sub-string check on it.

It can be done by converting it to std::string which will cause copying the data. Is it possible to somehow convert it to std::string_view and do search on it to avoid copying it.

1 Answers

Provided that char is 8 bits on your system (most systems are), you can simply reinterpret_cast the vector's data to char* and make a view from that, eg:

std::vector<uint8_t> data;
...
std::string_view sv(reinterpret_cast<char*>(data.data()), data.size());
Related