Assume that I have this message.
message A {
repeated float w = 1 [packed = true];
}
How can I initialize w in my Code? Can I do any better than this?
a = A()
for (int i = 0 ; i < n; ++i)
a.add_w(0);
Yes, repeated fields retain the order of items.
repeated : this field can be repeated any number of times (including zero) in a well-formed message. The order of the repeated values will be preserved.
gRPC services provide two ways of returning datasets, or lists of objects. The Protocol Buffers message specification uses the repeated keyword for declaring lists or arrays of messages within another message. The gRPC service specification uses the stream keyword to declare a long-running persistent connection.
a.w()
or a.mutable_w()
will return a google::protobuf::RepeatedField<float>
which provides some additional options. For instance, you could call a.mutable_w()->Reserve(n)
to pre-allocate space in advance, to avoid the usual strategy of re-allocating every time the size doubles. You can also use Resize(n)
followed by mutable_data()
to get direct access to the underlying buffer, but this probably won't provide much speed benefit over Reserve(n)
followed by your loop.
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