On Wed, Jul 7, 2010 at 8:06 AM, Robert Jones <robertgbjones@gmail.com> wrote:
On Wed, Jul 7, 2010 at 3:30 AM, Max S. Kaznady <max.kaznady@gmail.com> wrote:
Hi Robert,

Yep, the following works great. Not sure why the same code doesn't
work when I have it in my larger project, but I guess that's for me to
figure out.

There is still the problem with the std::for_each, see below:

#include <iostream>
#include <vector>
#include <algorithm>
#include <math.h>
#include "boost/bind.hpp"
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/io.hpp>

int main( )
{
 boost::numeric::ublas::vector<double> v(10);
 double exponent = 2.1;
 std::fill(v.begin(), v.end(), 8.0);
 // The following works just fine:
 std::transform( v.begin(), v.end(), v.begin(), boost::bind( pow, _1,
exponent ) );
 // But the for_each doesn't apply the power function, just leaves
the vector unaltered
 std::for_each( v.begin(), v.end(), boost::bind( pow, _1, exponent ) );
 // Print the result
 std::cout<< v << std::endl;

 return 0;
}

Compiled with: g++ -O2 -Wfatal-errors -Wall -g -ansi
-I/usr/local/boost/include -o main main.cpp


Hi Max

I haven't taken the time to try this, but does this do the trick?

std::for_each(v.begin(), v.end(), boost::bind(pow, boost::ref(_1), exponent));

Cheers

- Rob.
 

Forget that, it was complete gibberish. Your example doesn't do as you expect
because std::pow does not alter its argument, but rather returns a result. You have
to do something with the result of std::pow, hence my original use of transform.

To understand this look at this example.

#include <vector>
#include <algorithm>
#include <math.h>
#include "boost/bind.hpp"

void my_pow( double & val, double exponent )
{
    val = pow( val, exponent );
}

int main( )
{
    std::vector<double> v;
    double exponent = 2.1;

    std::for_each( v.begin(), v.end(), boost::bind( my_pow, _1, exponent ) );
}

HTH

- Rob.