C++ List Sorting – How to Sort a List of Structs

c++listsortingstruct

I have a C++ code where there is a struct and list of structs. In my struct, the first element is a string. In list of struct, how do I sort with the first element of the structure so that after sorting all the elements in the list will be arranged alphabetically?

struct samplestruct
{
    string Name;
    int Number
};
samplestruct obj_samplestruct;
vector<samplestruct> List;
obj_samplestruct.Name = "Tom";
obj_samplestruct.Number = 1;
list.push_back(obj_samplestruct);

obj_samplestruct.Name = "Jerry";
obj_samplestruct.Number = 2;
list.push_back(obj_samplestruct);

obj_samplestruct.Name = "Tom";
obj_samplestruct.Number = 3;
list.push_back(obj_samplestruct);

Now in the above code, how do I sort as per Name in the structure so that in the list, the members should be arranged alphabetically.

Best Answer

The sort function requires something that can be called with two arguments and returns a bool, this could be a lambda function:

sort( list.begin( ), list.end( ), 
    []( const samplestruct& a, const samplestruct&b ){
    return a.Name < b.Name;
} );

By default it looks for an operator<, so this would work as well:

bool operator<( const samplestruct& a, const samplestruct&b ){
    return a.Name < b.Name;
}
sort( list.begin( ), list.end( ) );
Related Question