简体   繁体   中英

How to use Google Protobuf Map in C++?

I am attempting to use the new protobuf Map functionality in C++.

The following was done on Ubuntu 14.04 with gcc 4.9.2 C++14 and 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. But the protobuf implementation always yields the following compiler error:

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.

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.

As Pixelchemist pointed out, the problem is that map is a pointer so the [] operator does not work.

Thus, the pointer needs to be dereferenced first. *map[key] also does not work, as the compiler first parses [] and then the * . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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