1

This is my code inside myCode.h:

#include <set>

using namespace std;

bool MyObjectComp(const MyObject& lhs, const MyObject& rhs) {
    return lhs.mTick < rhs.mTick;
}

typedef std::multiset<MyObject, MyObjectComp> MyObjectMultiSet;

but it says that function MyObjectComp is not a type name. Where should I place it?

markzzz
  • 47,390
  • 120
  • 299
  • 507
  • Possible duplicate of [Using custom std::set comparator](http://stackoverflow.com/questions/2620862/using-custom-stdset-comparator) – ashiquzzaman33 Apr 20 '16 at 14:17

2 Answers2

4

The template parameter for std::multiset expects a type, MyObjectComp is not a type but is instead a function name. You can either use decltype to get its type like

typedef std::multiset<MyObject, decltype(MyObjectComp)*> MyObjectMultiSet;

Or you could specify the type yourself like

typedef std::multiset<MyObject, bool(*)(const MyObject&, const MyObject&)> MyObjectMultiSet;

Also note the generally a functor/lambda is more efficent than using a function as the compiler can more easily optimize the code. I would suggest using

struct MyObjectComp {
    bool operator()(const MyObject& lhs, const MyObject& rhs) {
        return lhs.mTick < rhs.mTick;
    }
};

typedef std::multiset<MyObject, MyObjectComp> MyObjectMultiSet;

or

auto MyObjectComp = [](const MyObject& lhs, const MyObject& rhs) {
                            return lhs.mTick < rhs.mTick;
                        };

typedef std::multiset<MyObject, decltype(MyObjectComp)> MyObjectMultiSet;
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • Ok. But once I got `std::multiset MyObjectMultiSet;`, where do I start to "insert" to this list? Should I init it before? I can't do `MyObjectMultiSet.insert(elem)` :( – markzzz Apr 20 '16 at 14:36
  • @paizza Does it give you an error? If so what error? You may want to ask a new question though to resolve that as it will get more attention. – NathanOliver Apr 20 '16 at 14:40
1

The template argument should be a type, that is why you get a compilation error. This is how you should define MyObjectComp to avoid that issue:

struct MyObjectComp {
    bool operator()(const MyObject& lhs, const MyObject& rhs) {
        return lhs.mTick < rhs.mTick;
    }
}

or you could use a lambda:

auto MyObjectComp = []()(const MyObject& lhs, const MyObject& rhs) {
    return lhs.mTick < rhs.mTick;
};

typedef std::multiset<MyObject, decltype(MyObjectComp)> MyObjectMultiSet;
Marko Popovic
  • 3,999
  • 3
  • 22
  • 37