简体   繁体   English

如何在C ++中使用Google Protobuf Map?

[英]How to use Google Protobuf Map in C++?

I am attempting to use the new protobuf Map functionality in C++. 我试图在C ++中使用新的protobuf Map功能。

The following was done on Ubuntu 14.04 with gcc 4.9.2 C++14 and protobuf 3.0.0-alpha-4: 以下是在Ubuntu 14.04上使用gcc 4.9.2 C ++ 14和protobuf 3.0.0-alpha-4完成的:

Message definition: 消息定义:

message TestMap {
     map<string,uint64> map1 = 1;
}

Then, I tried to compile the following example program: 然后,我尝试编译以下示例程序:

auto test = debug::TestMap::default_instance();
auto map = test.mutable_map1();
string key = "key";
uint64 val = 20;
map[key] = val;

Acccessing the map using the [] syntax works totally fine for std::unordered_map. 使用[]语法处理地图对std :: unordered_map完全正常。 But the protobuf implementation always yields the following compiler error: 但protobuf实现总是会产生以下编译器错误:

error: no match for ‘operator[]’ (operand types are ‘google::protobuf::Map<std::basic_string<char>, long unsigned int>*’ and ‘std::string {aka std::basic_string<char>}’)

I do not understand why this operator is not known, because the header file google::protobuf::Map is clearly found and this should be an elementary operation. 我不明白为什么不知道这个运算符,因为清楚地找到了头文件google :: protobuf :: Map ,这应该是一个基本的操作。

Do you have any idea what goes wrong here? 你知道这里出了什么问题吗? I would welcome any example of using the new protobuf maps, as I haven't found any online after researching for hours. 我欢迎使用新的protobuf地图的任何例子,因为我在研究了几个小时之后没有找到任何在线。

As Pixelchemist pointed out, the problem is that map is a pointer so the [] operator does not work. 正如Pixelchemist指出的那样,问题是map是一个指针,因此[]运算符不起作用。

Thus, the pointer needs to be dereferenced first. 因此,需要首先取消引用指针。 *map[key] also does not work, as the compiler first parses [] and then the * . *map[key]也不起作用,因为编译器先解析[]然后再解析* The following does work: 以下工作:

(*map)[key] = val;

Although this is a quite basic problem, this represents a good learning opportunity for C++ and Protocol Buffers. 虽然这是一个非常基本的问题,但这代表了C ++和Protocol Buffers的良好学习机会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM