C++ 如何使用函子对集合进行排序

C++ 如何使用函子对集合进行排序,c++,sorting,set,C++,Sorting,Set,嘿,我正在尝试使用afunctor对集合容器进行排序: struct CompareCatId : public std::binary_function<Vehicale*, Vehicale*, bool> { bool operator()(Vehicle* x, Vehicle* y) const { if(x->GetVehicleType() > y->GetVehicleType()) re

嘿,我正在尝试使用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;
}
};
出于某种原因,我得到了这个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>'
错误C2784:'reverse_iterator::difference_type std::operator-(const std::reverse_iterator&,const std::reverse_iterator&)':无法从'std::_Tree_const_iterator'推断'const std::reverse_iterator&'的模板参数
提前感谢你的帮助

嘿,我正在整理我的布景

ofc我没有忘记包括算法


您正在尝试对集合进行排序吗?这是没有意义的,也不会起作用的

集合是一个排序关联容器。一旦创建了集合,就不能对其重新排序。排序机制是集合本身的模板参数

因此,如果要以不同的顺序表示集合中的元素,有三个选项:

1) 将元素从原始集合复制到另一个容器(向量可能是最简单的),并对其排序

2) 使用不同的排序机制重新定义集合


3) 创建一个排序索引,将引用以不同的顺序映射到集合。

std::set对象是一个有序容器。可以将排序比较函子指定为第二个模板参数。使用的默认函数对象是std::less。

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

只需跳过排序(开始、结束)一切都会好起来的

此外,在本例中,函子模拟operatorGetVehicleType()GetVehicleType(); } };
是的,我尝试了排序(m_VehicleSet->begin(),m_VehicleSet->end())@Nadav:A
set
总是被排序的,不需要调用
std::sort
。哦,现在我看到了Nadav的评论。当然,对已排序的容器进行排序是行不通的。请发布您试图编译的实际代码。请先创建一个最小版本,然后再发布…及其拼写的Vehicle=),该comparator与问题中的一个不同;如果类型相同,还有第二个字段要比较。
 sort(m_vehiclesSet->begin(),m_vehiclesSet->end()); 
 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>'
struct CompareCatId : public std::binary_function<Vehicale*, Vehicale*, bool>
{
    bool operator()(Vehicle* x, Vehicle* y) const
    {   
        return x->GetVehicleType() < y->GetVehicleType();
    }
};