Search code examples
c++sortingvectorprivate-members

Sorting a vector in C++ by accessing a private member


I'm working on a project and I have to sort a vector, but I'm facing some difficulties.

class CService {
    private:
        string m_strSeller;
    public:
        // Other stuff.
};

class CAnalizeTime : public CService {
    private:
        void sortSellerVector () {
            vector<CService>m_vData;
            m_vData.push_back(m_strSeller);
            sort(m_vData.begin(), m_vData.end());
        }
};

I'm getting 2 errors on my void sortSellerVector() function:

  1. Cannot access private member declared in class 'CService'
  2. Cannot convert from 'class std::basic_string,class std::allocator >' to 'const class CService'

My questions are:

  1. How do you access a private member from another class?
  2. What exactly does the second error mean? I don't understand it.

Solution

  • To be able to sort a vector<CService>, the easiest way is to just give CService an operator< overload that std::sort can use to sort the elements. Of course, this operator< overload will have access to m_strSeller if it is a member function:

    class CService {
      private:
        string m_strSeller;
      public:
        bool operator<(const CService& other) const
        {
          return m_strSeller < other.m_strSeller;
        }
        /////..... (other stuff)
    };
    

    Then you can just do:

    vector<CService> vData;
    // Push some CServices into the vector
    sort(vData.begin(), vData.end());
    

    An alternative method is to have a comparison function that you give to std::sort to use. You can make it a friend of CService so that it can access the private member:

    class CService {
      private:
        string m_strSeller;
      public:
        friend bool compare(const CService&, const CService&);
        /////..... (other stuff)
    };
    
    bool compare(const CService& a, const CService& b)
    {
      return a.m_strSeller < b.m_strSeller;
    }
    

    Which you then use like so:

    vector<CService> vData;
    // Push some CServices into the vector
    sort(vData.begin(), vData.end(), compare);