简体   繁体   English

如何汇总protobuf消息

[英]How to aggregate protobuf message

I have a protobuf message look like below: 我有一个protobuf消息,如下所示:

message sample {
    optional int32 value1 = 1;
    optional int32 value2 = 2;
    ...
    optional int64 valuen = n;
}

There are lots of objects and I want to aggregate these objects. 有很多对象,我想聚合这些对象。 The normal method is: 正常方法是:

void aggregate(ample& msg1, sample& msg2) {
  msg1.set_value1(msg1.value1() + msg2.value1());
  msg1.set_value1(msg1.value2() + msg2.value2());
  ...
  msg1.set_value1(msg1.valuen() + msg2.valuen());
}

Is there any way to simplify the code? 有什么方法可以简化代码吗? I try MergeFrom method but it replace the optional field not add. 我尝试使用MergeFrom方法,但它替换了不添加的可选字段。

Protocol buffer is not build for that kind of manipulation. 协议缓冲区不是为这种操纵而建立的。 The problem is if you have a shallow structure of the message then it will be ok, if you are uncertain about the message structure that will create problem every time you have to change the message structure. 问题是,如果您的消息结构较浅,那么就可以了,如果您不确定每次将要更改消息结构时都会造成问题的消息结构。

MergeFrom is great if you have 2 messages and you want to join their structures together, but you do not want this. 如果您有2条消息并且想要将它们的结构连接在一起,但您不希望这样做,那么MergeFrom非常有用。

What you could have is a repeated field ( std vector ) to store the elements and aggregate them. 您可能会有一个重复字段(std vector)来存储元素并将它们聚合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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