Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

override map::compare with lambda function directly

Trying to override map::compare function using lambda, it seems that the following solution works.

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

But, I had to define cmp first and use it later.
Can I do this without defining 'cmp'?

like image 629
MBZ Avatar asked Aug 04 '13 16:08

MBZ


1 Answers

No, you can't use lambda in unevaluated context -- i.e. template parameters as in your example. So you must define it somewhere else (using auto) and then use decltype... the other way, as it was mentioned already is to use an "ordinal" functors

If your question is about "how to use lambda expression *once* when define a map" you can exploit implicit conversion of lambdas to std::function like this:

#include <iostream>
#include <functional>
#include <map>

int main()
{
    auto m = std::map<int, int, std::function<bool(const int&, const int&)>>{
        [](const int& a, const int& b)
        {
            return a < b;
        }
    };
    return 0;
}

you may introduce an alias for that map type to reduce typing later...

like image 103
zaufi Avatar answered Oct 04 '22 09:10

zaufi