Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

c++ - Using Lambdas in Maps

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

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

but that fails with

error: type/value mismatch at argument 3 in template parameter list for ‘template<class _Key, class _Tp, class _Compare, class _Alloc> class std::map’

error: expected a type, got ‘{}’

error: invalid type in declaration before ‘;’ token

Any advice?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...