简体   繁体   English

如何 append 多个元素到协议缓冲区中的重复字段?

[英]How to append multiple elements to a repeatedField in Protocol buffers?

Given a message给定消息

message My_msg{
  repeated double my_arr = 1;
}

How can one append elements into the field?如何才能将一个 append 元素放入现场?

There is an answer for copying/moving already allocated full arrays by overwriting the current contents , but what if there is already some data in the filed, which needs to be kept as it is? 通过覆盖当前内容复制/移动已分配的完整 arrays 有一个答案,但是如果该字段中已经有一些数据需要保持原样怎么办?

Is using the below code to do it safe?使用以下代码是否安全?

void set_data(std::vector<double> table, My_msg* message){ /* suppose message is valid */
  message->mutable_my_arr()->Resize(message->my_arr_size() + table.size(),0);
  message->mutable_my_arr()[message->my_arr_size() - table.size()] = {table.begin(),table.end()};
}

I don't think your sample code would build.我认为您的示例代码不会构建。 My_msg::mutable_my_arr() returns a pointer to a RepeatedField (not the first element of an array). My_msg::mutable_my_arr()返回一个指向RepeatedField的指针(不是数组的第一个元素)。 Trying to index it would segfault at best.尝试对其进行索引充其量会出现段错误。

In terms or performance, if you have your data in an std::vector you will always need to copy - so you could just try to make that faster.就性能而言,如果您将数据保存在std::vector中,您将始终需要复制 - 因此您可以尝试加快速度。

You can call RepeatedField::Reserve before.您可以在之前调用RepeatedField::Reserve Then you can either write a loop, or use RepeatedFieldBackInserter :然后你可以写一个循环,或者使用RepeatedFieldBackInserter

void set_data(const std::vector<double>& table, My_msg* message){
  message->mutable_my_arr()->Reserve(message->my_arr_size() + table.size());
  std::copy(
      table.begin(),
      table.end(), 
      RepeatedFieldBackInserter(message->mutable_my_arr()));
}

Just call My_msg::add_my_arr :只需调用My_msg::add_my_arr

void set_data(std::vector<double> table, My_msg* message) {
    for (auto ele : table) {
        message->add_my_arr(ele);
    }
}

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

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