【问题标题】:2 different sorts, 1 functor2 种不同的类型,1 个函子
【发布时间】:2023-03-11 21:21:01
【问题描述】:

我有一个仿函数用于比较两个值,如果这两个值相等,则它依赖于按字母顺序排序。

这是一个名为 test 的类的示例函子,该类具有属性访问器 GetValue 和 GetName

struct test_comp {
    bool operator() (const test* a, const test* b) const {
        if(a->GetValue() == b->GetValue()) {
            return a->GetName() < b->GetName();
        } else {
            return a->GetValue() > b->GetValue();
        }

    }
};

这将有效地按最大的 value 对 STL 容器进行排序,如果然后在每个值内按字母顺序排列 name

然后我尝试输出两件事:

STL 容器的前 N ​​个元素和 STL 的后 N 个元素,如果值相等,则按字母顺序排序。

这是我的代码,使用 STL 列表test_list:

test_list.sort(test_comp);

cout << "First 5:" << endl;
n = 1;
for (auto it = test_list.begin(); it != test_list.end(); ++it) {
    cout << (*it)->GetName() << " " << (*it)->GetValue() << endl;
    if(++n > 5) {
        break;
    }
}

cout << "Last 5:" << endl;
m = 5;
for (auto it = test_list.rbegin(); it != test_list.rend(); ++it) {
    cout << (*it)->GetName() << " " << (*it)->GetValue() << endl;
    if(--m < 1) {
        break;
    }
}

例如考虑这个列表:

name  value
A     1
B     4
C     1
A     3
B     3
C     3
A     4
B     1
C     4

正确输出:

前 5 名:

name  value
A     4
B     4
C     4
A     3
B     3

最后 5 个:

name  value
A     1
B     1
C     1
A     3
B     3

我的输出:

前 5 名:

name  value
A     4
B     4
C     4
A     3
B     3

最后 5 个:

name  value
C     1
B     1
A     1
C     3
B     3

正如您在“Last 5”中看到的,字母排序保持不变,当反向迭代时,字母排序现在下降,而我仍然希望它上升。我知道如何做我想做的唯一方法是使用 2 个仿函数和 2 个排序。我很好奇是否有一种方法可以使用 1 个函子和 1 个排序。

编辑 1:

修正了 a 与 a 比较的一些错别字。

编辑 2:

更清楚输出差异

【问题讨论】:

  • 您正在以相反的顺序遍历最后 5 个元素。那么,您为什么希望按字母顺序查看它们呢?正如人们所期望的那样,它是反字母顺序的。
  • 是的,代码按预期工作。我更想知道有人如何在不使用 2 个几乎相同的仿函数和 2 个排序的情况下按照我想要的方式解决它。
  • 当我测试您的代码时,我得到的结果与您报告的非常不同:coliru.stacked-crooked.com/a/b7d2007d48a18208
  • 对不起,我有一些相似的 a 和 b coliru.stacked-crooked.com/a/d405e241a729dd78
  • @BHare:嗯,看起来问题解决了,对吧?

标签: c++ sorting stl functor


【解决方案1】:

我不确定,但这看起来非常非常错误

bool operator() (const test* a, const test* b) const {
    if(a->GetValue() == a->GetValue()) { //comparing a to a?
        return a->GetName() < b->GetName();
    } else {
        return a->GetValue() > a->GetValue(); //comparing a to a?
    }

}

也许如果您将a 与b 进行比较,您会得到更好的结果。

编辑后,现在您的“正确输出”看起来很疯狂,对我来说毫无意义,而您的“我的输出”看起来是正确的,只是相反。因为,你知道,你把它印反了。问题是您正在反向打印最后 5 个。

【讨论】:

  • 对不起,我让访问器对 SO 更通用,忘记更改复制的代码。固定
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-10
  • 1970-01-01
  • 1970-01-01
  • 2016-12-14
  • 2013-04-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多