ProgLearner
ProgLearner

Reputation: 181

STL sort by variable and then in ascending order

How could I sort alphabetically and then by int variable in the class? How can I combine them, so if counter is the same, it will return in alphabetical order?

// 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(), ??)

Upvotes: 3

Views: 155

Answers (2)

vishal129
vishal129

Reputation: 105

Using the above combined Sort function (Modified the sort as you want alphabetical first and the int value later.), you can call sort something like this:

Assuming you had 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);

Upvotes: 1

davidhigh
davidhigh

Reputation: 15478

Extend your two criteria to a lexicographic comparison:

bool combinedSort(const Page &a, const Page &b)
{
    return a.counter > b.counter || (a.counter == b.counter && a.name < b.name);
}

Upvotes: 5

Related Questions