?

Log in

No account? Create an account

Previous Entry | Next Entry

C++ lambdas

I was catching up on C++11 last night. Learned about lambdas, and started playing around with them. A neat addition. But did they provide full closure capability, like creating a snapshot of state that the function can privately modify? Looked like no, and I was all set to be disappointed.

But at a job interview yesterday, I learned about the mutable keyword, which was described as letting you modify const things, like deep in a const object hierarchy. "Why would you even do that?" was my first reaction, though I can vaguely imagine why, "for the same reason that Haskell's purity annoyed me."

So I remembered that, and figured I would try adding mutable to the lambda. Ka-ching!


#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    vector  v;
    for (int i=1; i<=10; i++) {
        v.push_back(i);
    }
    int sum=0;
    for_each(begin(v), end(v), [sum](int n) mutable {sum+=n; cout << sum << endl;});
    cout << sum << endl;

}
</vector></iostream></algorithm>


Output:
1
3
6
10
15
21
28
36
45
55
0

Not that you need the external sum here, you could drop it and have [sum=0] for the lambda, but it illustrates the idea. Which isn't obscure, I saw it in the docs I was reading shortly after returning to them, but still, I found this on my own.

I've been applying to a bunch of C++ jobs more because of experience than because of any deep love for the language, but features like this and auto (type inference) and others from C++11/14 make it a lot more appealing.

See the comment count unavailable DW comments at http://mindstalk.dreamwidth.org/460210.html#comments

Profile

Phoenix
mindstalk
Damien Sullivan
Website

Latest Month

November 2017
S M T W T F S
   1234
567891011
12131415161718
19202122232425
2627282930  

Tags

Powered by LiveJournal.com
Designed by Lilia Ahner