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.
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.
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.
The pairs in a set are stored in sorted order, sorted by the key i.e. the first value of the pair.
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.
#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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With