Current protoc version: 25.0
I am trying to add x elements into a repeated field at once, and I thought the best way to do it was to use the Resize function. However When I try to compile the following errors emerge:
‘class google::protobuf::RepeatedPtrField<Elem>’ has no member named ‘Resize’; did you mean ‘size’?
Minimum reproducible example ( Neither function call compiles ):
message Elem{
uint32 a = 1;
}
message Container{
repeated Elem elems = 5;
}
Container c;
c.mutable_elems()->Resize(5);
c.mutable_elems()->Resize(5, Elem());
Why might this be and is there any way to avoid boilerplate in this case?
(boilerplate like for(int i = 0; i <5; ++i)c.add_elems();
)
repeated Elem elems
contains a vector-like container of pointers to other repeated messages. c.mutable_elems()
returns this container of pointers RepeatedPtrField<Elem>
, which does not have the Resize()
method. Having this method would have little sense, you unlikely want to fill the container with several null pointers or a same single pointer repeated in several new elements.
RepeatedPtrField<Elem>
has the Reserve()
method, that can be used before an insertion loop for better performance:
Container c;
c.mutable_elems()->Reserve(5);
for (int i = 0; i < 5; ++i)
c.add_elem(...); // or c.AddAllocated(...);