在 protobuf 列表的开头插入项目

Inserting an item at the beginning of a protobuf list

本文关键字:开头 插入项目 列表 protobuf      更新时间:2023-10-16

>我正在尝试在 protobuf 消息列表的开头插入一个项目。 add_foo将项目追加到末尾。有没有一种简单的方法可以在开头插入它?

没有内置的方法可以使用协议缓冲区 AFAIK 执行此操作。 当然,文档似乎没有指出任何此类选项。

一种相当有效的方法可能是像往常一样在末尾添加新元素,然后反向迭代元素,将新元素交换在前一个元素的前面,直到它位于列表的前面。 因此,例如,对于像这样的protobuf消息:

message Bar {
  repeated bytes foo = 1;
}

你可以做:

Bar bar;
bar.add_foo("two");
bar.add_foo("three");
// Push back new element
bar.add_foo("one");
// Get mutable pointer to repeated field
google::protobuf::RepeatedPtrField<std::string> *foo_field(bar.mutable_foo());
// Reverse iterate, swapping new element in front each time
for (int i(bar.foo_size() - 1); i > 0; --i)
  foo_field->SwapElements(i, i - 1);
std::cout << bar.DebugString() << 'n';