Is there an implementation in the protocol buffers library that allows sorting the array that's specified as a repeated field? For e.g., say the array consists of items of a type that itself contains an index field based on which the array items need to be sorted. I couldn't find it, so guess I'll have to write one myself. Just wanted to confirm. Thanks.
Protobufs provide a RepeatedPtr interface, via the mutable_* methods, which can be sorted with the std::sort() template.
Unless the underlying type of the repeated field is a simple one, you'll likely want to use an overloaded operator<, comparator, or lambda to do so. An toy example using a lambda would be:
message StaffMember {
optional string name = 1;
optional double hourly_rate = 2;
}
message StoreData {
repeated StaffMember staff = 1;
}
StoreData store;
// Reorder the list of staff by pay scale
std::sort(store->mutable_staff()->begin(),
store->mutable_staff()->end(),
[](const StaffMember& a, const StaffMember& b){
return a.hourly_rate() < b.hourly_rate();
});
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