1

I wanted to know if it was possible to use a map with a google protocol buffer. I currently have something like this in my .proto file

message MsgA
{
required string symbol = 1 ;
optional int32  freq = 2   [default = 0]; 
}

message MsgB
{

   //What should I do to make a map<int,MsgA>
}

My question is in MsgB i would like to create a type that would be a map:: Any suggestion on how I could accomplish this ?

1 Answer 1

2

Do this:

message MapEntry
{
    required int32 mapKey  = 1;
    required MsgA mapValue = 2;
}

message MsgB
{
    repeated MapEntry = 1;
}

You will have to write your own code to convert the map to and from a MsgB, but that should be basically trivial.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for your reply. I am thinking about replacing the map with a vector. For this I will use the repeated field. Which I believe would act like a vector. Could you tell me how I can add items to a repeated field in C++
@MistyD: Use MapEntry& newMapEntry = myMsgB.add_mapentry();. Then fill out the fields in newMapEntry, which is now a reference to a newly-added map entry in message b.
I was looking at that in developers.google.com/protocol-buffers/docs/cpptutorial. Isnt it suppose to be MapEntry* newMapEntry = myMsgB.add_mapentry(); ? A pointer instead of a reference ?
Since it using reference i wanted to know how we reclaim the memory and when is it safe to delete the pointer ?
Sorry, you can do it that way. I meant MapEntry& newMapEntry = *myMsgB.add_mapentry();.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.