【问题标题】:STL sort by variable and then in ascending orderSTL按变量排序,然后升序
【发布时间】:2014-11-17 16:30:41
【问题描述】:

如何按字母顺序排序,然后按班级中的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(), ??)

【问题讨论】:

  • 您的意思是要按受欢迎程度对页面进行排序,然后按字母顺序对受欢迎程度相同的页面进行排序?
  • 是的,正是我想要实现的。这两个功能都有效,只是不知道如何将它们组合在一起。

标签: c++ sorting stl


【解决方案1】:

将您的两个条件扩展到lexicographic comparison

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

【讨论】:

  • 或者,您可以先排序,然后再进行稳定排序。
  • 条件可以改写为return std::tie(b.counter, a.name) &lt; std::tie(a.counter, b.name);
  • @Tim Seguine:这可能以某种方式起作用,但您不能只将alphaSort 传递给稳定的排序例程。它会重新排列您之前的顺序(除非偶然地由两个条件生成的分区匹配)。
  • @Jarod42:感谢您的评论,这确实更好一些——一旦您愿意对C++ reference 进行额外的间接处理。
  • @davidhigh 不不,你先alphaSort 然后用popularity 进行稳定排序。稳定排序不会改变具有相同流行度的项目的相对顺序,这意味着它们仍然按字母顺序排序。
【解决方案2】:

使用上述组合的 Sort 函数(先按字母顺序修改排序,然后再修改 int 值。),您可以像这样调用 sort:

假设你有一个页面向量

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

【讨论】:

  • 请注意,a.name &lt; b.name 不是 OP 在他的问题中所要求的——尽管考虑到他的接受,这似乎是他想要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-03
  • 2019-09-02
相关资源
最近更新 更多