Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    ++bufferDest;

    // 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 std way of doing things, but my implementation feels a bit clunky (specifically, having to explicitly increment the bufferDest after each copy). Is there a cleaner way to do this?

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

like image 476
Jon Cage Avatar asked Feb 04 '26 07:02

Jon Cage


1 Answers

I think this is much clearer.

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

    buffer.push_back('$');

    std::copy(source.begin(), source.end(), std::back_inserter(buffer));
    std::copy(id.begin(), id.end(), std::back_inserter(buffer));
    std::copy(payload.begin(), payload.end(), std::back_inserter(buffer));
}
like image 109
Danh Avatar answered Feb 05 '26 21:02

Danh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!