【发布时间】:2025-12-30 11:55:10
【问题描述】:
我有这个代码:
std::vector<uint8_t> getWriteBuffer()
{
boost::property_tree::ptree jsonTree=getJson(); //This function returns a json in a ptree
// I have this code, but is there any faster way to do this?
std::ostringstream jsonStream;
boost::property_tree::write_json(jsonStream, jsonTree);
std::string jsonString = jsonStream.str();
std::vector<uint8_t> output(jsonString.begin(), jsonString.end());
return output;
}
作为代码,我可以通过将 Ptree 写入字符串流,然后将其转换为字符串,然后将其复制到缓冲区来做到这一点。
有没有更快的方法来做到这一点?
【问题讨论】:
-
@ildjarn 是的,假设我想将序列化数据作为缓冲区通过方法发送到其他地方。我需要一个包含 json 字符串的向量(向量只是表示简单缓冲区的一种方式)
-
也许您可以改进界面以采用
span或string_view(甚至boost::asio::const_buffer)而不是特定的东西(如vector<unsigned char>)。这样你就可以解决任何未来使用的问题(假设调用者在某种连续的 POD 容器中有缓冲区)
标签: c++ boost stdvector boost-propertytree