Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting the items in repeated field of a message in Google Protocol Buffers

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.

like image 819
AarCee Avatar asked Aug 15 '13 06:08

AarCee


1 Answers

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();
          });
like image 146
Gavin Duggan Avatar answered Nov 16 '22 03:11

Gavin Duggan