Thomas Thomas - 3 months ago 10
C++ Question

define a custom Compare for multiset

function<bool(const pair<int, int>&, const pair<int, int>&)> cmp = [](const pair<int, int> & left, const pair<int, int> & right){if(left > right) return true;};

//multiset<pair<int, int>, function<bool(const pair<int, int>&, const pair<int, int>&)> mt(cmp);
multiset<pair<int, int>, decltype(cmp)> mt1(cmp);

cout<<typeid(decltype(cmp)).name()<<endl<<typeid(cmp).name()<<endl;


the comment code(
mt
) will make an error whereas the line below(
mt1
) won't.

I tried to
cout
the name of two type and they are the same.


Besides, I also tried like this:


multiset<pair<int, int>, const function<bool(const pair<int, int>&, const pair<int, int>&) &> mt(cmp);


or

multiset<pair<int, int>, function<bool(const pair<int, int>&, const pair<int, int>&) &> mt(cmp);


All of them don't work.

So what is the type of the second argument exactly? If I don't use
decltype
, how can I declare it?

Answer

Look carefully at your code, you lost a >.

multiset<pair<int, int>, function<bool(const pair<int, int>&, const pair<int, int>&)>> mt(cmp);
//                                                                                   ~

Using decltype should be a good idea.

BTW: You should return something when if returns false in lambda. Or just return left > right;.

Comments