有没有更简洁的方法将 std::string 组合成 std::vector<char>?

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

我有一些代码可以将各种元素组合到一个缓冲区中。我的代码看起来像这样:

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();
}

该方法调用如下:

std::vector<char> buffer;

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

CreatePacket(source, id, payload, buffer);

我对 std 的做事方式还不太了解,但我的实现感觉有点笨拙(具体来说,必须在每次复制后显式递增 bufferDest)。有更简洁的方法吗?

我的编译器不支持 C++11,如果有区别的话。

我觉得这样就清楚多了

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));
}

除了可以使用 std::copy 中的 return 值之外,它几乎是干净的,从而摆脱了 bufferDest:

的显式增量
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
    bufferDest = std::copy(source.begin(), source.end(), bufferDest);

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

您可以只使用适当的 vector::insert() overloadvector 的末尾附加 string 的内容(无需使用 std::copy 使代码复杂化或 std::back_inserter 如其他答案所示),例如:

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

所以你的函数看起来像这样:

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('$');

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