views:

89

answers:

2

hey, i implemented the following functor:

struct CompareCatId : public std::binary_function<Vehicle*, Vehicle*, 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;
    }
};

when i try to define a vector as the following i am getting alot of errors :

vector<Vehicle*,CompareCatId>* m_vehiclesVector;

thanks in advance for your help.

+4  A: 

vector does not take a functor, so you can't.

vector has two template parameters: the type of object to be stored and the allocator to be used (the allocator is optional; by default it will use std::allocator<T>).

The ordered associative containers (e.g., map and set) allow you to specify a comparison function because they are ordered containers: they have to keep their elements in some order.

If you want to keep the elements of the vector sorted you need to sort them yourself, either by inserting each new element into the correct position in the vector such that it always stays sorted or by sorting the vector after you have finished inserting elements. Alternatively, you can use one of the ordered associative containers, like set.

James McNellis
Putting a functor in a vector shouldn't be any problems if it's assignable\copy-constructable?
Viktor Sehr
@Viktor: Yes, you can create a vector of functors assuming they meet those requirements; but that's not what the OP is trying to do. The OP is trying to provide a functor to the vector, presumably to have the vector use it to keep the vector sorted.
James McNellis
@Viktor - true, but OP is trying to attach functor to vector<Vehicle>
Steve Townsend
A: 

vector isn't a sorted container and as such doesn't accept a comparison type.

I think you're looking for std::set<Vehicle*,CompareCatId>* m_vehiclesVector;

Mark B