How to use function from <cmath> with Boost.Lambda?

I am trying to convert all elements of the vector v to my log values ​​with some other arithmetic operations (not in the code). How can I use Boost.Lambda to achieve this?

As I said, there are a few more arithmetic operations, so the expression with Boost.Bind does not work for me (too complicated, too long, unreadable).

I don't want to use lambdas C ++ 11. But ... will anything change?

My code is similar:

 #include <boost/lambda/lambda.hpp> #include <cmath> #include <vector> void testLambda() { using namespace boost::lambda; std::vector<double> v; v.push_back(1); v.push_back(2); v.push_back(3); std::transform(v.begin(), v.end(), v.begin(), _1 / 0.5); // works std::transform(v.begin(), v.end(), v.begin(), log(_1) / 0.5); // produces error //std::transform(v.begin(), v.end(), v.begin(), std::log(_1) / 0.5); // produces error //std::transform(v.begin(), v.end(), v.begin(), static_cast<double(*)(double)>(std::log)(_1) / 0.5); // produces error } 

When I try to compile the code, MSVC2010 gives an error:

 Error 1 error C2665: 'log' : none of the 3 overloads could convert all the argument types C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\math.h(120): could be 'double log(double)' C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\math.h(527): or 'float log(float)' C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\math.h(575): or 'long double log(long double)' while trying to match the argument list '(boost::lambda::placeholder1_type)' 

Update 1: I don’t want to write functors for this, I think I have to have a dozen of them, what then?

Update 2: I can do this with C ++ 11 lambdas, but this is not what I ask :

  std::transform(v.begin(), v.end(), v.begin(), [](const double & x) { return log(x) / 0.5; }); 
+4
source share
1 answer

What about the correct Lamba C ++ 11? MSVC2010 has limited support, but simple math should work fine.

 std::transform(v.begin(), v.end(), v.begin(), [](const double& x) { return log(x); }); 

Or a solution to an old school problem:

 struct f { double operator()(const double& x) { return log(x); } } std::transform(v.begin(), v.end(), v.begin(), f); 

In any case, I don't see the need for fancy lambda stuff in the code you posted, as you seem to change the vector elements in place:

 std::vector<double> v; v.push_back(1); v.push_back(2); v.push_back(3); for(const std::vector<double>::iterator it = v.begin(); it != v.end(); ++it) { /* fancy math stuff here */ *it = log(*it); } 

This is IMHO the cleanest way to do this. My final C ++ solution (by far the most expressive and simplest of all alternatives) would be the following:

 for(auto&& x : v) { /* fancy math stuff here */ x = log(x); } 
+2
source

Source: https://habr.com/ru/post/1492102/


All Articles