proto3 中的 map 类型

.proto

syntax = "proto3";
option optimize_for = SPEED;

message TestStruct
{
    map<int32,string> data = 1;
}

.cpp

#include <iostream>
#include <cstdio>
#include <list>
#include <string>
#include <cstdint>
#include <ctime>
#include "msg.pb.h"
#include "google/protobuf/text_format.h"
using namespace google::protobuf;

int32_t main()
{
    TestStruct tSt1;
    tSt1.mutable_data()->insert({ 1, "str1" });
    tSt1.mutable_data()->insert({ 1, "str11" });
    tSt1.mutable_data()->insert(MapPair<int32_t, std::string>(2, "str2"));
    std::string data;
    tSt1.SerializeToString(&data);

    TestStruct tSt2;
    tSt2.ParseFromString(data);
    for(auto it = tSt2.data().cbegin(); it != tSt2.data().cend(); ++it)
    {
        std::cout << it->first << " " << it->second << std::endl;
    }

    std::string strTest;
    TextFormat::PrintToString(tSt2, &strTest);
    std::cout << strTest << std::endl;

    std::cin.get();
    return 0;
}

运行结果:

注意:当再次插入重复的key的时候,插入操作将会失败.

posted @ 2018-01-19 01:48  你好阿汤哥  Views(17734)  Comments(0Edit  收藏  举报