如何使用Functor对集合进行排序

Nad*_*ern 2 c++ sorting set

嘿,我正在尝试使用afunctor对我的set容器进行排序:

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;
}
};
Run Code Online (Sandbox Code Playgroud)

这就是我定义我的Set的方式:

      set<Vehicale*,CompareCatId>* m_vehicalesSet;
Run Code Online (Sandbox Code Playgroud)

并且我不忘记包括算法

我尝试使用这一行进行排序:

 sort(m_vehiclesSet->begin(),m_vehiclesSet->end()); 
Run Code Online (Sandbox Code Playgroud)

由于某种原因,我得到这个akward错误:

 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>'
Run Code Online (Sandbox Code Playgroud)

在此先感谢您的帮助.

Vik*_*ehr 6

std::set当您向其中插入元素时,A 会自动排序.您不需要(也不能)手动对其进行排序.

跳过sort(begin, end);,一切都会好的!

此外,在这种情况下,你的仿函数模仿operator <,所以你要编写的是:

struct CompareCatId : public std::binary_function<Vehicale*, Vehicale*, bool>
{
    bool operator()(Vehicle* x, Vehicle* y) const
    {   
        return x->GetVehicleType() < y->GetVehicleType();
    }
};
Run Code Online (Sandbox Code Playgroud)