在 protobuf 列表的开头插入项目
Inserting an item at the beginning of a protobuf list
>我正在尝试在 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';
相关文章:
- 如何在C++中.txt文件的开头插入字符串
- C++ 在字符的开头插入字符
- 使用代码块在链表的开头插入节点
- 无法在我的链接列表中插入项目,head始终为NULL
- 如何在单向链表的开头插入
- 如何在C 中以给定索引列表中的项目插入项目
- 无法在 c++ 链表的开头插入
- 如何在滚动区域中动态插入项目并在QT中加载滚动条
- 在 std::forward_list 的开头插入元素
- 如何在结果列表的开头插入生成的列表
- 在linkedList C++的开头插入
- 在另一个字符*C++的开头插入一个字符*
- 在 protobuf 列表的开头插入项目
- 如何在 doxygen 的注释中插入项目名称
- Qt内置数据结构中是否有忽略重复插入项目的数据结构
- 在链表的开头插入时读取内存时出错
- 在我的排序列表中插入项目时出现问题
- 如何在矢量的开头插入元素
- 关于在链表开头插入节点(程序未正确执行)
- 如何在std::map中插入项目而不违反MISRA C++2008必需规则5-2-12