Search code examples
c++classsortingprivate

Sorting custom object by private members


I found a lot of explanations on sorting functions, but I could not manage to implement one with my code.

I have a structure like this:

class Out{
  public:
     const std::map<std::string,In>& getListIn()const;
  private:
     std::map<std::string,In> listIn;

     class In{
        public:
           const float& getScore();
        private :
              float score;
     };
};

I want to sort my listIn by score (max to min). I tried to overload operator> or to create my own function:

 std::map<std::string,Out::In> notVisited = listIn;
 bool Out::In::compareCostScore (const std::pair<std::string,Out::In>& v1,const std::pair<std::string,Out::In>& v2){
        return (v1.second.getCostScore() > v2.second.getCostScore());
 }
 std::sort(notVisited.begin(), notVisited.end(), Out::In::compareCostScore());

But the function is not known. Or :

std::sort(notVisited.begin(), notVisited.end(),[] (const std::map<std::string,Out::In>& v1, const std::map<std::string,Out::In>& v2) {return (v1.second.getCostScore() < v2.second.getCostScore()};)

I'm having some problems with compatibility of type or privacy. Maybe that's because I'm trying to sort this private member out of the class... Thanks

Edit: I made it \o/ :

bool operator > (const In& v) const{
                return (score > v.score);
}
std::vector<Out::In> notVisited;
for( std::map<std::string,Out::In>::iterator it = listIn.begin(); it != listIn.end(); ++it ) {
    notVisited.push_back( it->second );
}
std::sort(notVisited.begin(), notVisited.end(), std::greater<Out::In>());

Thanks for your explications about map


Solution

  • Since your inner class has only one field and it has a getter (you might want to make this getter const const float& getScore() const ) you can simply change Out::in declaration to public and get rid of the problem. But if it is an extract and there are more logic after Out::in that you want to hide from public access then you can define your comparator as a friend function like this:

    class Out{
    /* ... */
    public:
        friend bool Out::In::compareCostScore (const std::pair<std::string,Out::In>& v1,const std::pair<std::string,Out::In>& v2);
    }