Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Lambdas in Maps

Tags:

c++

c++11

lambda

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?

like image 910
ygr Avatar asked Jan 05 '12 02:01

ygr


People also ask

What is map filter and lambda in Python?

The map() function in Python takes in a function and a list as an argument. The function is called with a lambda function and a list and a new list is returned which contains all the lambda modified items returned by that function for each item.

When should lambdas be used?

Lambda functions are used when you need a function for a short period of time. This is commonly used when you want to pass a function as an argument to higher-order functions, that is, functions that take other functions as their arguments.

What is lambda in Python Why is it used?

We use lambda functions when we require a nameless function for a short period of time. In Python, we generally use it as an argument to a higher-order function (a function that takes in other functions as arguments). Lambda functions are used along with built-in functions like filter() , map() etc.

What are the common functional programming methods that use lambdas?

Lambda expressions — also known as “anonymous functions” — allow us to create and use a function in a single line. They are useful when we need a short function that will be used only once. They are mostly used in conjunction with the map, filter and the sort methods, which we will see later in the article.


1 Answers

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.

like image 93
Benjamin Lindley Avatar answered Sep 23 '22 15:09

Benjamin Lindley