I want a custom comparator for the following code. However, I am not allowed to overload operator(), std::less, std::greater.
I tried to achieve this using lambda but gcc won't allow me to use auto as a non-static member. Any other way to make this work?
#include <iostream>
#include <map>
#include <set>
class Test
{
public:
// bool operator () (const int lhs, const int rhs) { // not allowed
// return lhs > rhs;
// };
using list = std::multiset<int /*, Test*/>;
std::map<const char*, list> scripts;
};
int main()
{
Test t;
t.scripts["Linux"].insert(5);
t.scripts["Linux"].insert(8);
t.scripts["Linux"].insert(0);
for (auto a : t.scripts["Linux"]) {
std::cout << a << std::endl;
}
std::cout << "end";
}
Edit: With lambdas
class Test
{
public:
auto compare = [] (const int a, const int b) { return a < b;}
using list = std::multiset<int, compare>; //here
std::map<const char*, list> scripts;
};
Error:
'auto' not allowed in non-static class member
auto compare = [] (const int a, const int b) { return a < b;}
I assume that you are not allowed to overload
operator()of theTestclass, but could be that of other class. If so, create a internalprivatefunctor which overloadsoperator()and that could be part of the aliasusing list = std::multiset<int, Compare>;Update: After researching a while, I found a way to go which does work† with a lambda function.
The idea is to use the
decltypeofstd::multisetwith custom lambda compare as the key of thestd::mapscripts. In addition to that, provide a wrapper method for inserting the entries to theCustomMultiList.Complete example code: (See live)
† Until c++20 lambda are not default constructable and copyable. But, the std::map::operator[] does requered the mapped_type to be copy constructible and default constructible. Hence the insertion to the value of the
scriptsmap(i.e. tostd::multiset<int, decltype(/*lambda compare*/)>) using subscription operator ofstd::mapis only possible from from C++20.