Search code examples
c++lambdasetpredicate

Create set with custom comparator passed as lambda


I was writing the solution for this and needed to create a set, well actually an unordered_map from int to my custom set, without further ado, this is what I came up whith:

auto comparator = [](pair<int, int> a, pair<int, int> b) {return a.second == b.second ? a.first < b.first : a.second < b.second; };
unordered_map<int, set < pair<int, int>,decltype(comparator) >> H;

The rest of code is not relevant. Here the compiler complains that

"Severity   Code    Description Project File    Line    Suppression State
<lambda_6dd753bdcbaf959c162af7914f0815bf>(void)': attempting to reference a deleted function"

Can anyone please describe that is compiler trying to tell me, or even better if you could hint what I have done wrong. Thanks in advance.


Solution

  • It's telling you that it needs to invoke the default c'tor for that lambda type you defined. However, it is only in C++20 and beyond that a captureless lambda is default-constructible. Prior to that all lambdas cannot be default constructed, they only spring into existence from a corresponding lambda expression (or copied of course).

    I recommend using a custom functor type for this.

    struct Comparator {
      bool operator()(pair<int, int> a, pair<int, int> b) 
      { return a.second == b.second ? a.first < b.first : a.second < b.second; };
    };
    
    unordered_map<int, set < pair<int, int>, Comparator  >> H;