Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sort a set using a Functor

Tags:

c++

sorting

set

hey, i am trying to sort my set container using afunctor:

struct CompareCatId : public std::binary_function<Vehicale*, Vehicale*, bool>
{
    bool operator()(Vehicle* x, Vehicle* y) const
    {   
        if(x->GetVehicleType() > y->GetVehicleType())
            return true;
        else if (x->GetVehicleType() == y->GetVehicleType() 
                               && x>GetLicenseNumber() > y->GetLicenseNumber())
                return true;
            else
                return false;
}
};

and this is how i defined my Set :

      set<Vehicale*,CompareCatId>* m_vehicalesSet;

and ofc i did not forget to include algorithm

i tried using this line for sorting :

 sort(m_vehiclesSet->begin(),m_vehiclesSet->end()); 

for some reason i am getting this akward error :

 error C2784: 'reverse_iterator<_RanIt>::difference_type std::operator -(const std::reverse_iterator<_RanIt> &,const std::reverse_iterator<_RanIt2> &)' : could not deduce template argument for 'const std::reverse_iterator<_RanIt> &' from 'std::_Tree_const_iterator<_Mytree>'

thanks in advance for your help.

like image 244
Nadav Avatar asked Aug 24 '26 04:08

Nadav


2 Answers

A std::set is sorted automatically as you insert elements into it. You don't need to (and you can't) sort it manually.

Just skip sort(begin, end); and everything will be just fine!

Also, in this case your functor mimics operator<, so all you have to write is:

struct CompareCatId : public std::binary_function<Vehicale*, Vehicale*, bool>
{
    bool operator()(Vehicle* x, Vehicle* y) const
    {   
        return x->GetVehicleType() < y->GetVehicleType();
    }
};
like image 138
Viktor Sehr Avatar answered Aug 25 '26 19:08

Viktor Sehr


hey, i am trying to sort my set

ofc i did not forget to include algorithm

Are you trying to std::sort a set? That is meaningless and won't work

like image 31
fredoverflow Avatar answered Aug 25 '26 20:08

fredoverflow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!