2种不同的排序,1个函子

2 different sorts, 1 functor

本文关键字:1个 排序 2种      更新时间:2023-10-16

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

下面是一个名为test的类的函子示例,该类具有属性访问器GetValueGetName

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:

修正了与进行比较的一些拼写错误

编辑2:

更清楚输出差异

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

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?
}
}

也许如果你比较ab,你会得到更好的结果。

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