I have some entries in the repeated field in my proto. Now I want delete some of them. How can I accomplish this? There is a function to delete the last element, but I want to delete arbitrary elements. I cant just swap them because the order is important.
I could swap with next until end, but isn't there a nicer solution?
According to the API docs, there isn't a way to arbitrarily remove an element from within a repeated field, just a way to remove the last one.
What I usually do in these cases is to create a new Protobuf (PB) message. I iterate the repeated fields of the existing message and add them (except the ones you don't want anymore) to the new PB message.
Although there's no straight-forward method you still can do this (for custom message using reflection). Code below removes
count
repeated field items starting fromrow
index.Here is example:
Protobuf v2
You can use the
DeleteSubrange(int start, int num)
inRepeatedPtrField
class.So if you want to delete a single element then you have to call this method as
DeleteSubrange(index_to_be_del, 1)
. It will remove the element at that index.Protobuf v3 update
As mentioned in the comments,
iterator RepeatedField::erase(const_iterator position)
can delete at arbitrary position