对对象中C++排序函数的比较器定义
下面是我的代码。操作员功能工作不正常。任何帮助都将不胜感激。通常,排序按升序排序。我想定义运算符,使其按降序排序对对象中C++排序函数的比较器定义,c++,C++,下面是我的代码。操作员功能工作不正常。任何帮助都将不胜感激。通常,排序按升序排序。我想定义运算符,使其按降序排序 #include<iostream> #include<cstdio> #include<algorithm> #include<vector> #include<utility> using namespace std; typedef pair<int,int> pii; typedef pair<in
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<utility>
using namespace std;
typedef pair<int,int> pii;
typedef pair<int,pii> pwp;
bool operat(pwp a, pwp b){
if(a.first > b.first){
return true;
}else if(a.second.first > b.second.first) {
return true;
}else if (a.second.second > b.second.second) { return true;}
return false;
}
int main(){
vector<pwp> inp;
pwp obj1 = make_pair(1998,make_pair(3,24));
pwp obj2 = make_pair(1998,make_pair(3,21));
pwp obj3 = make_pair(1997,make_pair(3,24));
inp.push_back(obj1);
inp.push_back(obj2);
inp.push_back(obj3);
printf("Before sorting\n");
for(int i = 0 ; i< inp.size();i++){
pwp sth = inp[i];
printf("%d %d %d\n",sth.first,sth.second.first,sth.second.second);
}
sort(inp.begin(), inp.end(),operat);
cout<<"After soring"<<endl;
for(int i = 0 ; i< inp.size();i++){
pwp sth = inp[i];
printf("%d %d %d\n",sth.first,sth.second.first,sth.second.second);
}
return 0;
}
新的:
bool operat(pwp a, pwp b){
if(a.first > b.first){
return true;
}else if(a.first < b.first) return false;
else if(a.second.first > b.second.first) {
return true;
}else if (a.second.first < b.second.first) return false;
else if (a.second.second > b.second.second) { return true;}
return false;
}
在代码中:
bool operat(pwp a, pwp b){
if(a.first > b.first){
return true;
}else if(a.second.first > b.second.first) {
return true;
}else if (a.second.second > b.second.second) { return true;}
return false;
}
仅当a.first==b.first时,才应执行第二次比较;当a.second.first==b.second时,才应执行第三次比较。first带有比较运算符,如果其模板参数具有这些运算符,则可以使用这些运算符。因此,您可以简单地使用实例作为比较函子:
#include <functional> // for std::greater
operat = std::greater<pwp>();
std::sort(inp.begin(), inp.end(),operat);
如果您坚持自己实现词法比较逻辑,那么我建议如下:与其考虑如何正确比较std::pair,不如考虑通常如何比较std::pair。然后在比较std::pair时使用该逻辑。否。我想知道我的代码有什么问题。我不想知道methods@Programmer好吧,你的代码的错误是比较逻辑都搞乱了。修复方法是使用std::greater。如果你真的想重新发明轮子,那么我建议为一对轮子写一个比较,然后递归地使用它。为什么这个答案是-1?请解释一下?@billz这可能太容易了。太难搞砸了:-@Programmer我添加了一些建议。基本上,方法是分而治之。当您需要对std::pair进行比较时,您实际上不需要编写任何代码。您不需要严格的顺序吗。如果是这样,你就把它钉住了。摩奴的答案拼出来了,但是只要考虑一下这个,对于任何A和B,A.B在第一层都是错误的,但是在任何后续层都没有A==B的单一预校验。这也有助于考虑这一点。标准比较认为A==B等于!a2计算为false,然后第二个if检查2>1并返回true。。。。manu fatto也告诉过你如何修复它。
bool operat(const pwp& a, const pwp& b){ return a > b; }