tags:

views:

91

answers:

4

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.

+1  A: 

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

FredOverflow
yes i tried sort(m_vehiclesSet->begin(),m_vehiclesSet->end());
Nadav Stern
@Nadav: A `set` is always sorted, no need to call `std::sort`.
FredOverflow
Oh, now I see Nadavs comment. Sorting a sorted container won't work, of course.
Gabriel Schreiber
+1  A: 

A set is a sorted associative container. You can't re-sort a set once it has been created. The sorting mechanism is a template parameter of the set itself.

So if you want to represent the elements in a set in a different order, you have three options:

1) Copy the elements from the original set to another container (a vector might be simplest), and sort that.

2) Redefine the set using a different sorting mechanism

3) Create a sorted index that maps references to the set in a different order.

John Dibling
A: 

A std::set object is an ordered container. You can specify the sort comparison functor as the 2nd template argument. The default function object used is std::less.

Bukes
+5  A: 

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();
    }
};
Viktor Sehr
...and its spelled Vehicle =)
Viktor Sehr
That comparator isn't equivalent to the one in the question; there's a second field to compare if the types are equal.
Mike Seymour
Ah, you're right.
Viktor Sehr