How to use Google Protobuf Map in C++?

26,055

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.

Share:
26,055

Related videos on Youtube

Author by

Daniel Becker

Updated on July 09, 2022

Comments

  • Daniel Becker 5 months

    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.

    • Pixelchemist
      Pixelchemist over 7 years
      Your map variable seems to be a pointer. Did you try *map[key]?
    • Daniel Becker over 7 years
      @Pixelchemist: Do you want to post the answer or should I do it?
  • Kenton Varda
    Kenton Varda over 7 years
    FWIW, you could do: auto& map = *test.mutable_map1();, and then map[key] would work.
  • Daniel Becker over 7 years
    Thanks Kenton! That is much more reable and easier to maintain.
  • tigertang over 3 years
    map->operator[](key) = val;
  • Christopher Pisz
    Christopher Pisz about 2 years
    is mutable_map the only method to use to access the map?
  • Rick
    Rick about 2 years
    @ChristopherPisz No. test.map1() gives you a const reference, if you only need acess instead of modification. Doc is here developers.google.com/protocol-buffers/docs/reference/…

Related