2种不同的排序,1个函子
2 different sorts, 1 functor
我有一个函子,用于比较两个值,如果这两个值相等,则依赖于按字母排序。
下面是一个名为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:
修正了与进行比较的一些拼写错误
编辑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++ 如何比较n个排序的整数向量以找到互元素?
- 合并两个排序链表时运行时出错
- 在 C++ 中合并两个排序链表
- 合并 2 个排序的链表。必需的成员函数 bool Merge(List342 &list1):
- 两个排序的链接列表C 的交点
- 合并两个排序的链表
- 合并两个排序的列表 - 不起作用
- 使用不同的比较函数合并两个排序的双向量
- 在完成对 k 个排序流进行排序的函数时需要帮助
- 如何在 c++ 中合并多个排序范围
- (C++)如何创建一个函数来接收两个排序的链表并返回出现在两个列表中的第三个元素列表
- 比较两个排序的数字向量(性能优先)
- 如何在c++中使用两个排序标准(对于一组对)创建有序集
- 合并两个排序的链接列表
- 在给定两个排序向量的情况下设置减法
- 在C++中合并两个排序的列表
- 将值插入到两个排序不同的 BST 中
- 合并两个排序的链表
- 合并两个排序的单向链表 [错误]