C++中是否有任何方法,它会根据对值的差异对一对向量进行排序。作为一个例子,假设我有4双向量对通过对元素的差异进行排序
1 3,
5 6,
2 3,
12 5,
如此,对差异是2 1 1 7,如果我按降序排序的排序矢量将是,
12 5,
1 3,
5 6,
2 3,
希望你明白我的问题是什么。有什么方法可以用这种方法对元素进行排序吗?
我试过这种方法来根据第一个或第二个元素对元素进行排序。但这不是我的问题。我的问题是我需要根据差异进行排序。
bool sortinrev(const pair<int,int> &a, const pair<int,int> &b){
return(a.first > b.first) ;
}
int main()
{
vector< pair <int,int> > pq;
for(int i=1; i<=4; i++){
int x,y;
cin >> x >> y;
pq.push_back(make_pair(x,y));
}
sort(pq.begin(), pq.end(), sortinrev);
for(int i=0; i<4; i++){
cout << pq[i].first << " " << pq[i].second << endl;
}
return 0;
}
的[排序函数(http://www.cplusplus.com/reference/algorithm/sort/)C++有可能需要一个函数指针作为参数。只要传递一个函数,按照你想要的方式比较对。 – scohe001
我只知道如何根据第一个元素或基于第二个元素对它进行排序。由于我不知道如何根据差异进行排序,所以我贴出来了解方式。然后我会尝试解决我的实际问题。 –
您可以将'compare'变量传递给'sort()'方法。请参阅@ scohe001在他的评论中的链接。 –