### Purpose of Lambda Functions?

Hello,

I came to internet, and found this:

http://en.wikipedia.org/wiki/Anonymous_function#C.2B.2B

I've heard about lambda functions earlier, but I don't quite catch it.
If I have any function, it has its own name, so I can call it and get expected results.
However, it just doesn't make sense to me if function doesn't have any name. How do I access it? What is it good for? Is it useful? When should I use it, and can I bypass it with ordinary function/something else?

Thank you :)
You can always replace a lambda expression with a class with a constructor, some data members, and a function call operator. They just save typing.
Here's an example:
with lambda:
 ``123456789101112131415161718192021`` ``````#include #include #include #include struct Record { std::string name; int data; }; int main() { std::vector v = {{"John", 10}, {"Andrew", -1}, {"Mary", 15}}; std::vector indices(v.size()); std::iota(indices.begin(), indices.end(), 0); // sort indices in the order determined by the name field of the records: std::sort(indices.begin(), indices.end(), [&](int a, int b) { return v[a].name < v[b].name; }); for(int idx: indices) std::cout << v[idx].name << ' ' << v[idx].data << '\n'; }``````

without lambda:

 ``12345678910111213141516171819202122232425262728`` ``````#include #include #include #include struct Record { std::string name; int data; }; struct Comparer { const std::vector& v; Comparer(const std::vector& v) : v(v) {} bool operator()(int a, int b) const { return v[a].name < v[b].name; } }; int main() { std::vector v = {{"John", 10}, {"Andrew", -1}, {"Mary", 15}}; std::vector indices(v.size()); std::iota(indices.begin(), indices.end(), 0); // sort indices in the order determined by the name field of the records: std::sort(indices.begin(), indices.end(), Comparer(v)); for(int idx: indices) std::cout << v[idx].name << ' ' << v[idx].data << '\n'; }``````
Topic archived. No new replies allowed.