现在我正在使用 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 andbytes
). Thevalue_type
can be any type.So, for example, if you wanted to create a map of projects where each
Project
message is associated with astring
key, you could define it like this:
map<string, Project> projects = 3;
关于c++ - 如何使用Google Protobuf实现Map结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26939842/