Jon Cage Jon Cage - 6 months ago 38
C++ Question

Is there a cleaner way to combine std::string into std::vector<char>?

I have some code that combines various elements into a buffer. My code looks something like this:

static void CreatePacket(const std::string& source, const std::string id, const std::string payload, std::vector<char>& buffer)
buffer.resize(source.size() + id.size() + payload.size());
std::vector<char>::iterator bufferDest = buffer.begin();

// Start the message
char MessageStart = '$';
*bufferDest = MessageStart;

// Copy the message source
std::copy(source.begin(), source.end(), bufferDest);
bufferDest += source.size();

// Copy the message id
std::copy(id.begin(), id.end(), bufferDest);
bufferDest += id.size();

That method is called as follows:

std::vector<char> buffer;

std::string source = "AB";
std::string id = "CDE";
std::string payload = "payload";

CreatePacket(source, id, payload, buffer);

I'm still a bit green on the
way of doing things, but my implementation feels a bit clunky (specifically, having to explicitly increment the
after each copy). Is there a cleaner way to do this?

My compiler doesn't support C++11 if that makes a difference.


You can just use a proper vector::insert() overload to append the content of a string at the end of the vector (no need to complicate the code using std::copy or std::back_inserter as showed in other answers), e.g.:

buffer.insert(buffer.end(), source.begin(), source.end());

So your function would look like this:

void CreatePacket(const std::string& source, 
                  const std::string& id, 
                  const std::string& payload, 
                  std::vector<char>& buffer)
    buffer.reserve(source.size() + id.size() + payload.size() + 1);


    buffer.insert(buffer.end(), source.begin(),  source.end() );
    buffer.insert(buffer.end(), id.begin(),      id.end()     );
    buffer.insert(buffer.end(), payload.begin(), payload.end());