Home > Enterprise >  multiset count method not working with class comparator
multiset count method not working with class comparator

Time:03-08

I have this struct

struct C {
    int ID;
    int age;
    C(int ID, int age) : ID{ID}, age{age} {}
};

I use a comparator function for a multiset

bool fncomp (const C& lhs, const C& rhs) {
    return lhs.age < rhs.age;
}

multiset<C, decltype(fncomp)*> ms{fncomp};
ms.emplace(1, 15);
...

// this works fine
ms.count(C(1, 15));

However if I use a class comparator, this is no longer working.

struct classcomp {
    bool operator() (const C& lhs, const C& rhs) {
        return lhs.age < rhs.age;
    }
};

multiset<C, classcomp> ms;
ms.emplace(1, 15);
...

// error
// ms.count(C(1, 15));

Anything makes the two different?

CodePudding user response:

Elaborating on my comment above:

multiset::count is a const member function, which means that it operates on a const multiset. This includes the member variables of the multiset. The comparator is a member variable of the multiset.

Since your classcomp::operator() is not marked const, it can't be called on a const object, and so it fails to compile.

This works for the function pointer example, because it's the pointer that is const in that case.

CodePudding user response:

bool operator() (const C& lhs, const C& rhs) const  {
    return lhs.age < rhs.age;
}

This would fix things to compile in this link you provided, courtesy of @Marshall -> https://stackoverflow.com/a/71384594/10630957

  • Related