Sorting a vector of pairs

user2633791 picture user2633791 · Aug 7, 2013 · Viewed 57.9k times · Source

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.

Answer

Hossein Nasr picture Hossein Nasr · Aug 7, 2013
#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.