我需要根据对的第一个元素按降序对对向量进行排序。如果该对的第一个元素相等,则比较基于第二个元素,第二个元素的值较小的元素必须首先出现。 例如:如果对是(0,0),(2,1),(1,2)那么结果必须是(2,1),(1,2),(0,0)。 (对的第二个元素是数组idex,以便在排序后使数组稳定。)
我已经编写了以下比较器函数,如下所示
bool comp(const pair<int, int> &a, const pair<int, int> &b) {
if (a.first > b.first) {
return 1;
} else if (a.first == b.first) {
if (a.second < b.second) {
return 1;
} else {
return 0;
}
}
}
对于上面的输入,我得到以下输出。 (1,2),(2,1),(0,0)但我期待上述输出,相同的功能在一些其他情况下产生所需的结果。这个比较器功能出了什么问题?
我称之为
sort(v.begin(), v.end(), comp);
其中v是成对的向量。
vector <pair<int, int> > v;
答案 0 :(得分:0)
比较算法的问题适用于a.first < b.first
的情况。您必须重写以下内容的逻辑:
bool comp(const pair<int, int> &a, const pair<int, int> &b) {
if (a.first == b.first) {
return (a.second > b.second);
} else {
return (a.first > b.first);
}
}
仅在second
相等时才使用first
的陪审员,因此首先使用==
检查第一个
答案 1 :(得分:0)
在a.first < b.first
的情况下,您没有处理代码。完整版将是:
bool comp(const pair<int, int> &a, const pair<int, int> &b) {
if (a.first > b.first) {
return true;
} else if (a.first < b.first) {
return false;
} else { // a.first == b.first
if (a.second < b.second) {
return true;
} else {
return false;
}
}
}
或者:
bool comp(const pair<int, int> &a, const pair<int, int> &b) {
if (a.first == b.first) {
if (a.second < b.second) {
return true;
} else {
return false;
}
}
else {
if (a.first > b.first) {
return true;
} else if (a.first < b.first) {
return false;
}
}
}
可以简化为:
bool comp(const pair<int, int> &a, const pair<int, int> &b) {
if (a.first == b.first) {
return a.second < b.second;
} else {
return a.first > b.first;
}
}