C++ 对成对的向量进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18112773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting a vector of pairs
提问by user2633791
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
这个向量已经填满了对。现在我想根据对内的双值对向量内的对进行排序
EXAMPLE:
例子:
suppose I have 3 pairs inside the vector. pair1 is at front and pair 3 is at end. pair2 is in the middle:
假设我在向量中有 3 对。pair1 在前面,pair 3 在末尾。pair2 在中间:
pair1(1, proc1)
pair2(3, proc2)
pair3(2.5, proc3)
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)
How could I do this? I am quite stuck.
我怎么能这样做?我很困。
回答by Hossein Nasr
#include <algorithm>
int main(){
std::vector<std::pair<double,Processor*>> baryProc;
std::sort(baryProc.begin(),baryProc.end());
}
Note that you do not need a custom comparator because the default comparator of pair does the thing you want. It first compares by the first element and if they are identical, it compares the second element in the pair.
请注意,您不需要自定义比较器,因为 pair 的默认比较器可以满足您的需求。它首先比较第一个元素,如果它们相同,则比较该对中的第二个元素。
回答by maditya
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:
在 C++ 中,您可以使用自定义比较器函数来指定在排序时如何确定一个元素是否排在另一个元素之前。在您的情况下,给定 2 对,您希望第一个元素的值较低的那个在另一个之前。您可以像这样编写比较器函数:
// 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);