我有一个仿函数,我用它来比较 2 个值,如果这 2 个值相等,则它依赖于按字母顺序排序。
这是一个名为 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
正如您在“最后 5 个”中看到的那样,字母排序得到了维护,当反向迭代时,字母顺序现在正在降序,而我仍然希望它是升序的。我知道如何做我想做的唯一方法是使用 2 个仿函数和 2 个排序。我很好奇是否有一种方法可以使用 1 个仿函数和 1 个排序。
编辑 1:
修正了 a 与 a 比较的一些拼写错误。
编辑 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?
}
}
也许如果您将 a
与 b
进行比较,您会得到更好的结果。
在你编辑之后,现在你的“正确输出”看起来很疯狂,对我来说毫无意义,而你的“我的输出”看起来是正确的,只是相反。因为,你知道,你把它印反了。问题是您正在反向打印最后 5 个。
关于c++ - 2种不同的种类,1个仿函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22209980/