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.

有帮助吗?

解决方案 2

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

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top