I'm trying to insert an item at the beginning of a protobuf list of messages. add_foo
appends the item to end. Is there an easy way to insert it at the beginning?
There's no built-in way to do this with protocol buffers AFAIK. Certainly the docs don't seem to indicate any such option.
A reasonably efficient way might be to add the new element at the end as normal, then reverse iterate through the elements, swapping the new element in front of the previous one until it's at the front of the list. So e.g. for a protobuf message like:
message Bar {
repeated bytes foo = 1;
}
you could do:
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With