Sorting STL by variable and then in ascending order
How could I sort alphabetically and then a variable int
in the class? How can I combine them, so if counter
is the same, it will return alphabetically?
// sort pages by its popularity
bool popularity(const Page &a, const Page &b) {
return a.counter > b.counter;
}
// alphabetical sort
bool alphaSort(const Page &a, const Page &b) {
return a.name < b.name;
}
// Combination?
sort(.begin(), .end(), ??)
+3
source to share
2 answers
Expand the two criteria into lexicographic comparison :
bool combinedSort(const Page &a, const Page &b)
{
return a.counter > b.counter || (a.counter == b.counter && a.name < b.name);
}
+5
source to share
Using the above combined sort function (changed the sort as you want alphabetically first and int value later.) You can call something like this:
Assuming you have a vector of pages
bool combinedSort(const Page &a, const Page &b)
{
return a.name < b.name || (a.name == b.name && a.counter < b.counter);
}
std::vector<Page> pages;
std::sort(pages.begin(), pages.end(), combinedSort);
+1
source to share