C++数据结构和pb数据结构的转换

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 Req{
  map<string, string> ext = 1;
  map<string, InnerStrMap> ext2= 2;
  repeated uint32 keys = 3;
};

赋值代码:

Req req;
// 1.ext
*req.mutable_ext() = {cpp_ext.begin(), cpp_ext.end()}; // 批量设置
req.mutable_ext()->insert({"keyA","valueA"}); //单个添加

// 2.ext2
for (const auto& pair : cpp_ext2) {
       InnerStrMap& innerMap = (*req.mutable_ext2())[pair.first];//获取到value的引用
        *innerMap.mutable_value() = {pair.second.begin(), pair.second.end()};// 批量赋值
}

// 3.keys repeat类型只能依次add
for (const auto& key : cpp_keys) {
     req.add_keys(key);
}

pb的map如何获取到key: .first/.second

1.3 两个proto之间的赋值

转自:https://maple.link/2021/12/27/protobuf-repeated-字段操作总结/

 

2.pb to C++

 

posted @ 2024-04-14 20:29  lypbendlf  阅读(21)  评论(0编辑  收藏  举报