c++ - 如何使用Google Protobuf实现Map结构

标签 c++ map protocol-buffers

现在我正在使用 Google protobuf,我想使用 Map 结构。但是我发现 Google protobuf 中没有实现这样的数据结构。

我的问题很简单。我有一个带有“页码(uint32_t)”和非常简单内容的结构。我想要的是使用此页码作为键,将内容作为值。这应该同时满足空间和速度要求。但是Protobuf中没有这样的数据结构。

我使用的方法是这样的:

message MyPageContent {
    required uint32 contentA = 1;
    required uint32 contentB = 2;
}

message MyTable {
    repeated MyPageContent table= 1;
}

总页数已知。所以在我的程序开始时,我将所有页面内容添加到表中,并带有一些特殊值(此值用于通知页面不存在,任何人都不应该使用该内容。)这样,我可以隐式使用页码索引。当一个页面准备好后,我将更改表中的相应值。人们直接使用页码作为索引来访问内容。这种方法占用了很多空间(很多页面还没有准备好,我只是在那里放了一些特殊的值让人们知道它还没有准备好。)但是访问时间很快。

另一种方法来做这样的事情:

message MyTable {
    repeated uint32 pageNum = 1;
    repeated MyPageContent myContent = 2;
}

这样,我就可以在表格准备好时向表格中添加一个页面。应该以这种方式限制表的大小。然而,人们必须首先进行线性搜索以查找页面是否在表格中。这会消耗很多时间。

基本上这就是我想在protobuf中使用Map结构的原因。它既节省空间又节省时间。

最佳答案

我不确定此更改何时发生,但目前(2015 年 4 月)ProtoBuf supports maps :

If you want to create an associative map as part of your data definition, protocol buffers provides a handy shortcut syntax:

map<key_type, value_type> map_field = N;

...where the key_type can be any integral or string type (so, any scalar type except for floating point types and bytes). The value_type can be any type.

So, for example, if you wanted to create a map of projects where each Project message is associated with a string key, you could define it like this:

map<string, Project> projects = 3;

关于c++ - 如何使用Google Protobuf实现Map结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26939842/

相关文章:

c++ - 我认为继承类构造函数不起作用。调用时调用的变量中的数据不正确

c++ - 如何使用基类指针引用派生类成员?

arrays - 将元素保存在Map/Array/Collection中……Grails

iphone - 如何以编程方式选择 map 图钉

pip - 轮文件:protobuf-3.4.0-py2.py3-none-any.whl中“none-any”是什么意思

c++ - 为什么不能将 char 指针定义为数组?

map - 在 golang 中分配给 map

protocol-buffers - 将 Protocol Buffer 集成到 WAF 中

python - grpc 字段 Message.Field .PeopleRequest.ages 的线路类型非法 : 2 (0 expected))

c++ - 关于在 C++ 中使用模板特征来选择数据类型