views:

156

answers:

1

I am learning the boost::lambda library and for that I wrote this sample code to convert an vector<A> into vector<int> by extracting the value from A object.

class A
{
public:
    A(int n) : m_n(n){}
    int get() const {return m_n;}

private:
    int m_n;

};

int _tmain(int argc, _TCHAR* argv[])
{
    using namespace boost::lambda;

    std::vector<A> a1;
    std::vector<int> a2;
    a1.push_back(A(10));
    a1.push_back(A(20));

    std::for_each(a1.begin(), a1.end(), bind(&std::vector<int>::push_back, var(a2), bind(&A::get, _1)));

    return 0;
}

I could get the for_each part to work after several tries. But I still don't look the like of it with those multiple binds. Is there any other way to write this. Preferably I would like to do something like: a2.push_back(bind(&A::get,_1));, but that doesn't compile.

+1  A: 

I don't think what you're trying to do is possible. for_each applies function to each element in the range, but you are trying to call two member functions and you'll have to bind them both. I think your code is the best you can do when using for_each. Lambda documentation looks very complete to me, but there is no example for what you're trying to do. I think it's for a reason, there is a more appropriate algorithm for this. As Kirill said it's transform.

std::transform(a1.begin(), a1.end(), std::back_inserter(a2), bind(&A::get, _1));
Nikola Smiljanić