【问题标题】:What is the fastest way to serialize a boost property tree (ptree) to a vector将boost属性树(ptree)序列化为向量的最快方法是什么
【发布时间】: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 字符串的向量(向量只是表示简单缓冲区的一种方式)
  • 也许您可以改进界面以采用spanstring_view(甚至boost::asio::const_buffer)而不是特定的东西(如vector&lt;unsigned char&gt;)。这样你就可以解决任何未来使用的问题(假设调用者在某种连续的 POD 容器中有缓冲区)

标签: c++ boost stdvector boost-propertytree


【解决方案1】:

我可能只是写入位于back_inserter_device 周围的流缓冲区上的流:https://www.boost.org/doc/libs/1_67_0/libs/iostreams/doc/classes/back_inserter.html

您还可以将其与 Boost 序列化结合使用,请参阅:

在这种情况下,使用 binary_oarchive 和 no_header 归档标志会减少数据量。

【讨论】:

    最近更新 更多