STL 按变量排序,然后按升序排序

STL sort by variable and then in ascending order

本文关键字:排序 升序 然后 STL 变量      更新时间:2023-10-16

如何按字母顺序排序,然后按类中的int变量排序?如何组合它们,因此如果counter相同,它将按字母顺序返回?

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

将两个标准扩展到词典比较:

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

使用上面的组合排序函数(修改了排序,因为您希望先按字母顺序排列,然后再按 int 值排列),您可以像这样调用排序:

假设您有一个页面向量

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);