对向量进行排序 [英] Sorting a vector of pairs
问题描述
我对排序向量对有一个疑问:
I have a question about sorting a vector of pairs:
std::vector<std::pair<double,Processor*>> baryProc;
此向量已被对填充. 现在我想根据向量对中的对值对进行排序
this vector is already filled up with the pairs. Now I wanted to sort the pairs inside the vector based on the double value inside the pair
示例:
假设向量中有3对. pair1在前面,pair 3在后面. pair2在中间:
suppose I have 3 pairs inside the vector. pair1 is at front and pair 3 is at end. pair2 is in the middle:
pair1(1, proc1)
pair2(3, proc2)
pair3(2.5, proc3)
现在我要基于double值对对进行排序.这样向量内的顺序是:
now i want to sort the pairs based on the double value. So that the order inside the vector is:
pair1(1, proc1)
pair3(2.5, proc3)
pair2(3, proc2)
我该怎么做?我很困.
推荐答案
在C ++中,您可以使用自定义比较器函数来指定如何确定排序时一个元素是否先于另一个元素.在您的情况下,给定2对,您希望第一个元素的值较低的那个在另一个元素之前.您可以像这样编写比较器函数:
In C++, you can have custom comparator functions that specify how to decide whether one element goes before another when sorting. In your case, given 2 pairs, you want the one with the lower value for the first element to go before the other one. You can write a comparator function like so:
// This function returns true if the first pair is "less"
// than the second one according to some metric
// In this case, we say the first pair is "less" if the first element of the first pair
// is less than the first element of the second pair
bool pairCompare(const std::pair<double, Processor*>& firstElem, const std::pair<double, Processor*>& secondElem) {
return firstElem.first < secondElem.first;
}
现在,将此函数传递给您的排序方法:
Now, pass this function into your sort method:
//The sort function will use your custom comparator function
std::sort(baryProc.begin(), baryProc.end(), pairCompare);
这篇关于对向量进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!