协议缓冲区可以序列化hash_multimap吗?

时间:2012-02-22 03:01:09

标签: c++ serialization hash hashmap protocol-buffers

我想序列化一个hash_multimap,protocal缓冲区是否支持它?我尝试过boost serializaitn,但它有关于hash_multimap的头文件混淆,所以我想试试谷歌协议缓冲区。

1 个答案:

答案 0 :(得分:2)

使用协议缓冲区有很多样板编码,你需要运行他们的protoc编译器从.proto文件生成实际的C ++,但除此之外它们很棒。

这是一个如何序列化和解析std :: hash_multimap

的示例

<强> my_hash_multimap.proto

message MyHashMultimap {
  message Pair {
    required int64 key = 1;
    required bytes value = 2;
  }
  repeated Pair pair = 1;
}

<强>的main.cpp

#include <algorithm>
#include <hash_map>
#include <iostream>
#include <string>
#include <utility>

#include "my_hash_multimap.pb.h"

int main() {
  std::hash_multimap<int, std::string> hm;
  hm.insert(std::make_pair(3, "three"));
  hm.insert(std::make_pair(2, "two"));
  hm.insert(std::make_pair(1, "one"));

  // convert std::hash_multimap to a protobuf MyHashMultimap
  MyHashMultimap proto_hm;
  std::for_each(hm.begin(),
                hm.end(),
                [&proto_hm](std::pair<int, std::string> p) {
    std::cout << p.first << "   " << p.second << std::endl;
    // add new Pair to proto_hm
    MyHashMultimap::Pair* proto_pair(proto_hm.add_pair());
    // set this Pair's values
    proto_pair->set_key(p.first);
    proto_pair->set_value(p.second);
  });

  // serialise proto_hm to a std::string
  std::string serialised_hm(proto_hm.SerializeAsString());

  // parse from this string to a new MyHashMultimap
  MyHashMultimap parsed_proto_hm;
  if (!parsed_proto_hm.ParseFromString(serialised_hm))
    return -1;
  std::cout << std::endl << parsed_proto_hm.DebugString() << std::endl << std::endl;

  // convert protobuf MyHashMultimap to a std::hash_multimap
  std::hash_multimap<int, std::string> parsed_hm;
  for (int i(0); i != parsed_proto_hm.pair_size(); ++i) {
    // check required fields are populated correctly
    if (parsed_proto_hm.pair(i).IsInitialized()) {
      // add the Pair to parsed_hm
      parsed_hm.insert(std::make_pair(parsed_proto_hm.pair(i).key(),
                                      parsed_proto_hm.pair(i).value()));
    }
  }

  std::for_each(parsed_hm.begin(),
                parsed_hm.end(),
                [](std::pair<int, std::string> p) {
    std::cout << p.first << "   " << p.second << std::endl;
  });

  return 0;
}