0

When I use the sort routine for a vector of Ereignis class instances, I am comparing some private members in this routine. As I don't have a direct access to them, I am using public methods instead:

bool sort(Ereignis *ereignis1, Ereignis *ereignis2)
{
    if (ereignis1->DatumHolen() < ereignis2->DatumHolen())
        return true;
    else if (ereignis1->DatumHolen() == ereignis2->DatumHolen())
    {
        if (ereignis1->VeranstaltungHolen()->RangfolgeAmGleichenTagHolen() < ereignis2->VeranstaltungHolen()->RangfolgeAmGleichenTagHolen())
            return true;
    }
    return false;
}
//---------------------------------------------------------------------------
stable_sort(ereignisse.begin(), ereignisse.end(), sort); 

Is this really a good practice? I mean, STL methods have been designed to work in a very fast way. For that reason it would make more sense to use the private members directly instead of loosing some time accessing the public methods instead.

Mauro
  • 31
  • 3
  • if those are simple 'getter' functions then any overhead will almost certainly be optimized away in a non debug build – pm100 May 10 '22 at 17:23
  • Note that `sort` does not meet the requirements of a strict weak ordering, and passing it to `std::stable_sort` exhibits undefined behavior. In particular, `sort(X, X) == true` when it's [required](https://en.cppreference.com/w/cpp/named_req/Compare) to be false. – Igor Tandetnik May 10 '22 at 18:06
  • I think, the answers help me. 'Friend' would be an option but as my 'getter' methods are very simple, I would let them do the job here. Regarding the last comment, why does my method not meet the requirements? When I have the same DatumHolen() and RangfolgeAmGleichenTagHolen() then the result is false which let the order of the class instances as they were before. WOuld I use normal 'sort' here, the sequence could be changed in that case. – Mauro May 10 '22 at 19:18

0 Answers0