0

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);
}
};
5
  • 2
    Post the actual code and the error messages generated by the compiler. Commented Jan 27, 2013 at 13:01
  • 3
    Does T2 have the < operator implemented? Commented Jan 27, 2013 at 13:02
  • 1
    Also, what is T2? Does operator< exist for this type? Commented Jan 27, 2013 at 13:03
  • T2 is appareantly std::string so i guess its not important YET. Something else is the problem. Commented Jan 27, 2013 at 13:03
  • @AdamVarhegyi: Why don't you post the actual code? Your question has no clue to the problem. Commented Jan 27, 2013 at 13:04

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I just wanted to tell the fact that you told me in one keyword "static", g++ told me in a 3 page error message :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.