Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use C++0x lambdas local variables for std::fill()?

So I was trying to test a lambda accessing local variables in the scope in which it is used, based roughly on a simple example by Bjarne on the C++0x FAQS page at: http://www2.research.att.com/~bs/C++0xFAQ.html#lambda

When I try this simple test code:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

//Test std::fill() with C++0x lambda and local var
void f (int v) { 
    vector<int> indices(v);
    int count = 0;
    fill(indices.begin(), indices.end(), [&count]() {
        return ++count;
    });

    //output test indices
    for (auto x : indices) {
        cout << x << endl;
    }
}

int main() {
    f(50);
}

I get the error:

required from 'void std::fill(_ForwardIterator, _ForwardIterator, const _Tp&) [with _ForwardIterator = __gnu_cxx::__normal_iterator<int*, std::vector<int> >, _Tp = f(int)::<lambda()>]'

I'm supposing this errmsg indicates the std::fill() signature requires a const Type& to use for the new value element assignment.

But if I'm to be able to use the fill() for this purpose, as indicated by Bjarne's example, won't I need to use a reference '[&count]' inside the lambda capture clause to be able to reassign the original indices element value with the incrementing count var via the 'return ++count;' lambda statement block?

I admit I don't quite understand all about these lambdas just yet! :)

like image 607
Bud Alverson Avatar asked Dec 02 '22 01:12

Bud Alverson


2 Answers

Bjarne's example doesn't compile. It can't compile, not unless they defined std::fill differently in C++0x. Maybe it was from a conceptized version of std::fill that could take a function, but the actual version of it (according to section 25.1 of N3242) takes an object, not a function. It copies that object into every element of the list. Which is what that one is trying to do.

The function you're looking for is std::generate.

like image 195
Nicol Bolas Avatar answered Dec 07 '22 22:12

Nicol Bolas


Try this:

for_each(indices.begin(), indices.end(), [&count](int& it) 
{        
    it = ++count;    
});

it is currently iterated content of vector, and is coming via reference.

like image 23
Ajay Avatar answered Dec 08 '22 00:12

Ajay