Problem with boosts lambda

A

Asif Zaidi

Hi:
Trying to compile the code below using lambda functionality and
getting all sorts of compile errors - plz advise
The code is (if working) trying to calculate the length of a vector.


Thanks

Asif

========

#include <numeric>
#include <algorithm>
#include <vector>
#include <cmath>
#include <functional>
#include <iostream>
#include<boost/lambda/lambda.hpp>

using namespace std;
using namespace boost;

using namespace std;
using namespace std::tr1;
using namespace std::tr1::placeholders;


int main()
{
vector<double> v;
v.push_back(7);
v.push_back(24);

cout << sqrt(accumulate(v.begin(), v.end(), 0.0, _1*_1 ) << endl;

return 0;
}
 
R

Robert Fendt

using namespace std::tr1;
using namespace std::tr1::placeholders;

At least my GCC (4.4) does not know tr1::placeholders without
'#include <tr1/functional>'. But: I would be quite surprised if
TR1 placeholders worked with boost::lambda. Also globally
importing namespaces is not good style (and for a reason).
cout << sqrt(accumulate(v.begin(), v.end(), 0.0, _1*_1 ) << endl;

There's a closing brace missing, it's the wrong placeholder
type, and "_1*_1" will not do what you want it to.


(1) Avoid global namespace imports like 'using namespace boost'
and especially 'using namespace std': it invites all kinds of
disasters.

(2) Remove the TR1 stuff and use boost placeholders with Boost.Lambda:

using namespace boost::lambda;

(3) The correct syntax for accumulating a sum of squares should be:

std::sqrt(std::accumulate(v.begin(), v.end(), 0.0, _1 + _2 *_2 ))

So the following should work:

----------------------------------------
#include <numeric>
#include <algorithm>
#include <vector>
#include <cmath>
#include <iostream>
#include <boost/lambda/lambda.hpp>

using namespace boost::lambda;

int main()
{
using namespace boost::lambda;

std::vector<double> v;
v.push_back(7);
v.push_back(24);

std::cout << std::sqrt(std::accumulate(v.begin(), v.end(), 0.0, _1 + _2 *_2 )) << std::endl;

return 0;
}
 
R

Robert Fendt

Correction. Of course the global-scope namespace import was an
unintended remnant/typo.

----------------------------------------
#include <numeric>
#include <algorithm>
#include <vector>
#include <cmath>
#include <iostream>
#include <boost/lambda/lambda.hpp>

int main()
{
using namespace boost::lambda;

std::vector<double> v;
v.push_back(7);
v.push_back(24);

std::cout << std::sqrt(std::accumulate(v.begin(), v.end(), 0.0, _1 + _2 *_2 )) << std::endl;

return 0;
}
----------------------------------------
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,810
Latest member
Kassie0918

Latest Threads

Top