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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>

struct Record {
    std::string name;
    int data;
};
int main()
{
    std::vector<Record> v = {{"John", 10}, {"Andrew", -1}, {"Mary", 15}};
    std::vector<int> 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>

struct Record {
    std::string name;
    int data;
};

struct Comparer {
    const std::vector<Record>& v;
    Comparer(const std::vector<Record>& v) : v(v) {}
    bool operator()(int a, int b) const { return v[a].name < v[b].name; }
};

int main()
{
    std::vector<Record> v = {{"John", 10}, {"Andrew", -1}, {"Mary", 15}};
    std::vector<int> 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.