Using Lambdas in Maps

后端 未结 1 1205
没有蜡笔的小新
没有蜡笔的小新 2020-12-09 07:59

I\'m trying to implement a map with a lambda function in C++11 as such

std::map te         


        
相关标签:
1条回答
  • 2020-12-09 08:44

    You need to pass the type of the lambda as a template argument, not the lambda itself. What you want is this:

    auto mycomp = [](const int&a, const int& b) { return a < b; };
    std::map<int, int, decltype(mycomp)> test(mycomp);
    

    Although in fact, since your lambda has no captures, it can actually be stored in a function pointer, so alternatively, you could do this:

    std::map<int, int, bool(*)(const int&,const int&)>
        test([](const int&a, const int& b) { return a < b; });
    

    Though I find the first much more readable. Although using the function pointer type is more versatile. i.e. It can accept any function pointer or non-capturing lambda that matches that signature. But if you change your lambda to be capturing, it will not work. For a more versatile version, you could use std::function, i.e:

    std::map<int, int, std::function<bool(const int&, const int&)>>
    

    That will work with any function, lambda(capturing or not) or function object, as long as the signature matches.

    0 讨论(0)
提交回复
热议问题