Dan*_*ker 7 c++ hashmap protocol-buffers c++14
我试图在C++中使用新的protobuf Map功能.
以下是在Ubuntu 14.04上使用gcc 4.9.2 C++ 14和protobuf 3.0.0-alpha-4完成的:
消息定义:
message TestMap {
map<string,uint64> map1 = 1;
}
Run Code Online (Sandbox Code Playgroud)
然后,我尝试编译以下示例程序:
auto test = debug::TestMap::default_instance();
auto map = test.mutable_map1();
string key = "key";
uint64 val = 20;
map[key] = val;
Run Code Online (Sandbox Code Playgroud)
使用[]语法处理地图对std :: unordered_map完全正常.但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>}’)
Run Code Online (Sandbox Code Playgroud)
我不明白为什么不知道这个运算符,因为清楚地找到了头文件google :: protobuf :: Map,这应该是一个基本的操作.
你知道这里出了什么问题吗?我欢迎使用新的protobuf地图的任何例子,因为我在研究了几个小时之后没有找到任何在线.
Dan*_*ker 10
正如Pixelchemist指出的那样,问题在于它map是一个指针,因此[]操作员无法工作.
因此,需要首先取消引用指针.*map[key]也不起作用,因为编译器先解析[]然后再解析*.以下工作:
(*map)[key] = val;
Run Code Online (Sandbox Code Playgroud)
虽然这是一个非常基本的问题,但这代表了C++和Protocol Buffers的良好学习机会.