Reputation: 111
I would like to pass a map "m" as a parameter for a comparator to be used with the sort function.
bool comparator(const myType A, const myType B, map<Mytype,int> m){
return m.find(A) < m.find(B);
}
Note that the comparator changes depending on m. Now, how could I use such comparator with the sort function? When I try the code below the compiler complains about the number of arguments in the comparator function.
void SortingVector(vector<myType> V, map<myType,int> m){
sort(V.begin(),V.end(),comparator);
}
So what is the easiest way, using STD machinery to define such a parameterized comparator?
Upvotes: 1
Views: 500
Reputation: 7591
Use a lambda closure:
void SortingVector(vector<myType>& V, const map<myType,int>& m){
sort(V.begin(),V.end(), [&m](const myType& A, const myType& B) {
return m.find(A) < m.find(B);
});
}
As a side note: I added various references, for both effectiveness and correctness, as your sort function otherwise would just sort a copied vector and throws it away after it ran out of scope.
Upvotes: 3