I got a vector containing pairs. My pairs have template parameters.
std::vector<std::pair<T1, T2> > myVector;
I would like to sort myVector by the pairs second data tag, so by the "value"(T2), not the "key"(T1). I saw here that i can use this sweet method:
std::sort(myVector.begin(), myVector.end(), mySortingFunc);
and this is my sortFunc:
bool mySortingFunc (std::pair<T1, T2> pair1, std::pair<T1, T2> pair2){
return (pair1.second<pair2.second);
}
and its not compiling, throwing me 10 kilometers long error. (i use g++) Any advice how should i do this?
Actual code:
template<typename T1, typename T2>
class OrderedMMap
{
std::vector<std::pair<T1, T2> > myVector;
public:
bool sortFunc (std::pair<T1, T2> pair1, std::pair<T1, T2> pair2) {
return (pair1.second<pair2.second);
}
void sortIt()
{
std::sort(myVector.begin(), myVector.end(), sortFunc);
}
};
Your sortFunc
is a non-static member function. That is the problem. A non-static member function can be invoked only on an object of the class; std::sort
cannot do that for you.
The easy fix is to make the function static
:
static bool sortFunc (std::pair<T1, T2> pair1, std::pair<T1, T2> pair2) {
return (pair1.second<pair2.second);
}
With the static
keyword, now it became just like regular function, which can be invoked without class instance, which means std::sort
will work now.
It would be good if the function accepts the arguments by const reference:
static bool sortFunc(std::pair<T1,T2> const& p1,std::pair<T1,T2> const& p2)
{
return p1.second < p2.second;
}
Hope that helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.