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?
- E D I T:
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
sortFuncis 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::sortcannot do that for you.The easy fix is to make the function
static:With the
statickeyword, now it became just like regular function, which can be invoked without class instance, which meansstd::sortwill work now.It would be good if the function accepts the arguments by const reference:
Hope that helps.