emesx
emesx

Reputation: 12755

Boost binding to member function of vector

Please help me with the following code. I need to add lengths of strings to a vector. I have no idea how to achieve it with boost. My best idea so far is:

boost::bind(add2Vect, boost::ref(lengths), L::_1)

Where add2Vect is a simple function that takes a vector, a string and add the length of the string to the vector. L is just a shorthand for boost::lambda

But this solution is bad, because I have to create a discrete function. That's not what lambdas should be about.

The code:

vector<string> strings;
strings.push_back("Boost");
strings.push_back("C++");
strings.push_back("Libraries");

vector<int> lengths;

for_each(strings.begin(), strings.end(),    
    // add lengths of strings to the vector 'lengths'

);

for_each(lengths.begin(), lengths.end(), 
    cout << L::_1 << " "
);  

Upvotes: 2

Views: 939

Answers (1)

Edward Strange
Edward Strange

Reputation: 40867

Boost.Bind and Boost.Lambda are not the same thing. You can't use lambda placeholders in bind unless you're using boost::lambda::bind.

Here's how you do what you seem to want:

std::transform(strings.begin(), strings.end(), std::back_inserter(lengths), 
               boost::bind(&std::string::size, _1));

If you really MUST use for_each:

std::for_each(strings.begin(), strings.end(), 
             boost::bind(&std::vector<int>::push_back,
               &lengths, boost::bind(&std::string::size, _1)));

But you should be using size_t rather than int.

Upvotes: 2

Related Questions