c++ - 如何序列化并通过网络发送 std::list?

标签 c++ stl

我需要通过网络连接发送存储在 std::list 中的动态大小的数据列表。我想使用序列化一次完成此操作,而不是单独发送每个元素。有什么建议吗?

最佳答案

boost::serialization使这很容易做到。它免费提供 std::list 所需的所有机制,您需要做的就是为您的列表包含的类型添加支持。 (如果它是“标准”类型,那么它也已经存在)

完整示例(改编自 this example ):

#include <list>
#include <sstream>

#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
// Provide an implementation of serialize for std::list
#include <boost/serialization/list.hpp>

class foo
{
private:
  friend class boost::serialization::access;
  template<class Archive>
  void serialize(Archive & ar, const unsigned int /*version*/)
  {
    // This is the only thing you have to implement to serialize a std::list<foo>
    ar & value;
    // if we had more members here just & each of them with ar
  }
public:
  int value;
};

int main() {
  std::stringstream out;

  // setup a list
  std::list<foo> list;
  {
    const foo f = {-1};
    list.push_back(f);
  }

  // serialize into the stream
  {
    boost::archive::binary_oarchive oa(out);
    oa << list;
  }

  // read the stream into a newlist
  std::list<foo> newlist;
  {
    boost::archive::binary_iarchive ia(out);
    ia >> newlist;
  }

  std::cout << newlist.front().value << std::endl;
}

这通过 std::stringstream 进行“发送”和“接收”,但是通过您选择的网络 API 将其调整为发送和接收应该是相当简单的。

关于c++ - 如何序列化并通过网络发送 std::list?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8141617/

相关文章:

c++ - 指针/引用数组?

c++ - 如何对齐结构数组,每个都需要对齐(SSE)

c++ - 什么是 Direct X 虚拟表?

c++ - MPI、C、派生类型、 vector 结构?

c++ - "vector iterator + offset out of range"断言有用吗?

c++ - 分配器 : how are the standard containers expected to work internally?

c++ - 非 B 树数据结构,其中昆虫以排序的方式完成,但我可以稍后从随机位置删除对象

c++ - 如何将 `std::vector<uchar>` 保存到 `std::ostream` 中?

c++ - 固定容量自定义 STL 容器的 max_size() 的正确值是多少?

c++ - 为什么在逗号分隔符上下文中将预增量的结果转换为 void?