C++資料結構和pb資料結構的轉換

lypbendlf發表於2024-04-14

1.C++ to pb

1.1 map巢狀物件結構

//pb資料結構
message Inner {
    repeated string codes = 1;
    map<string, string> ext = 2;
};

message Outer {
    map<int32, Inner> uint2Inner = 1;
    map<string, string> ext = 2;
};

賦值程式碼 :

Outer req;
req.mutable_ext()->insert({"keyA", "valueA"});

// uint2Inner
auto uint2inner    = req.mutable_uint2Inner();// 複雜的map成員新增元素
uint32_t a=5;
auto inner = (*uint2inner)[a];// map複雜物件新增成員
for (const auto& code : codes) {
    inner.add_codes(code); // repeated型別迴圈新增成員
}
inner.mutable_ext()->insert({"lat", "123"}); //map簡單型別的直接mutable&insert就行

1.2 巢狀map

// pb型別
message InnerStrMap {
  map<string, string> value = 1;
};
message PullLiveRoomListReq{
  map<string, string> ext = 1;
  map<string, InnerStrMap> ext2= 2;
  repeated uint32 keys = 3;
};

賦值程式碼:

2.pb to C++

相關文章