Sorting a vector of pairs [duplicate]

寵の児 提交于 2019-11-29 11:38:00

问题


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:

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.


回答1:


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);



回答2:


#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.



来源:https://stackoverflow.com/questions/18112773/sorting-a-vector-of-pairs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!