views:

66

answers:

2

I need to initialize some comparator of the new data type TType based on std::set with some object o of another class Object:

typedef std::set <unsigned int, sortSet(o)> TType

This declaration is otside the class (in header file). At the time of the declaration this object does not have to exist, it will be created later.

class sortSet
{
   private:
      Object o;

   public:
      sortSet(Object &oo): o(oo) {}
      bool operator() ( const unsigned int &i1, const unsigned int &i2 ) const
      {
         //Some code...
      }
};

If the declaration was inside some method (when object has already been created), situation would be quite simple... What can I do?

+2  A: 

The template parameter needs to be the type of the comparator, not a specific object of that type; you can provide a specific comparator object to be used in the std::set constructor:

typedef std::set<unsigned int, sortSet> TType;

Object o;
TType mySet(sortSet(o));
James McNellis
OK, it works now, thanx.
Rummy
A: 

I am not sure if I understood your actual question, however, the general idiom to use a custom comparator is shown in the following contrived example.

#include <set>

class foo {
  public:
    int i_;
};

struct foo_comparator {
    bool operator()( foo const & lhs, foo const & rhs ) {
        return lhs.i_ < rhs.i_;
    }
};

typedef std::set< foo, foo_comparator > foo_set;

int main() {
  foo_set my_foo_set;
}
ArunSaha