Deny
Deny

Reputation: 23

c++ Inset and read Map element in protobuf3

Here is the .proto which have one map:

map.proto

syntax = "proto3";

package demo;

message Person {

  map<string, int32> family_list = 4;

}

Now I insert key and value from the Write_impl.cc

auto map = test.mutable_family_list();
string key = "faimly";
int val =20;
(*map)[key] = val;
std::cout<<"map = "<<(*map)[key]<<std::endl;

Below I read the value of key family in read_impl.cc

auto test = demo::Person::default_instance();
auto map = test.mutable_family_list();
std::cout<<"map = "<<(*map)["faimly"]<<std::endl;

Problem: I get 0 when reading the value of key "family"

Upvotes: 0

Views: 695

Answers (1)

Azeem
Azeem

Reputation: 14587

You are using demo::Person::default_instance() which doesn't have the value you've stored earlier. It contains the default one.

You are using the subscript operator [] that doesn't throw an exception if the key is not found but the at() method does. You should use the at() method.

Here's an example of serialization and deserialization:

int main()
{
    // Serialization

    demo::Person sPerson;
    const auto mutable_family_list = sPerson.mutable_family_list();
    mutable_family_list->insert( { "abc", 42 } );
    std::cout << mutable_family_list->at( "abc" ) << '\n';

    const auto serialized = sPerson.SerializeAsString();

    // Deserialization

    demo::Person dPerson;
    if ( !dPerson.ParseFromString( serialized ) )
    {
        std::cerr << "Deserialization failed!\n";
        return -1;
    }

    const auto family_list = dPerson.family_list();
    std::cout << family_list.at("abc") << '\n';

    return 0;
}

Output:

42
42

Alternatively, you can find() first and then use the value like this:

const auto it = family_list.find( "abc" );
if ( it != family_list.end() )
{
    std::cout << it->second << '\n';
}

Upvotes: 1

Related Questions