Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a vector of pairs [duplicate]

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.

like image 232
user2633791 Avatar asked Aug 07 '13 20:08

user2633791


People also ask

Can you sort a vector of pairs?

Case 1 : Sorting the vector elements on the basis of first element of pairs in ascending order. This type of sorting can be achieved using simple “ sort() ” function. By default the sort function sorts the vector elements on basis of first element of pairs.

How do you sort two vectors simultaneously?

For example to sort two vectors i would use descending bubble sort method and vector pairs. For descending bubble sort, i would create a function that requires a vector pair. After that i would put your 2 vector values into one vector pair.

How is a set of pairs sorted?

The pairs in a set are stored in sorted order, sorted by the key i.e. the first value of the pair.

How do you sort a vector pair in ascending order?

Sort the vector of pairs in the Ascending Order in C++sort() function sorts the elements on the first pair of elements basis. Explanation: In this code, first, we declare the vector of pairs then we print them, we use the sort() function to sort the pairs in ascending order. After that, we print the sorted pairs.


1 Answers

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

like image 118
Hossein Nasr Avatar answered Oct 03 '22 04:10

Hossein Nasr