我有一些代碼將各種元素組合到一個緩衝區中。我的代碼看起來是這樣的:是否有更簡潔的方式將std :: string合併到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。
你不需要明確遞增'bufferDest','的std :: copy'返回到您 –