Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append string data to std::vector<std::byte>>

Tags:

c++

std

c++17

byte

I'm implementing a HTTP server and the API I follow define the raw response data as a std::vector<std::byte>>.

I store http responses headers as std::string in my code and at some point I have to write them to to raw response data before sending it back.

The thing is, I cannot find a clean way to write/append data from a std::string to my std::vector<std::byte>> (by clean way I mean not looping on the string and appending each char).

What is the best way to do that ?

Side question: What is the best way to read a string from a std::vector<std::byte>> ?

like image 221
Théo Champion Avatar asked Apr 29 '26 12:04

Théo Champion


1 Answers

Just use the ranged-insert overload (#4):

void extend(std::vector<std::byte>& v, std::string const& s) {
    auto bytes = reinterpret_cast<std::byte const*>(s.data());
    v.insert(v.end(), bytes, bytes + s.size());
}

You can read char as byte, it's a permitted alias.

like image 91
Barry Avatar answered May 02 '26 04:05

Barry