Boost logo

Boost Users :

From: Todd Greer (TGreer_at_[hidden])
Date: 2006-08-22 16:31:09


Minkoo Seo wrote:
> vector< pair<string, int> > subjects;
> subjects.push_back(make_pair("Math", 90));
> subjects.push_back(make_pair("English", 86));
> subjects.push_back(make_pair("Physics", 88));
> subjects.push_back(make_pair("Biology", 97));
>
> long total;
> total = accumulate(subjects.begin(), subjects.end(), 0,
> _1 + bind(&pair<string, int>::second, _2));

> This is a simple score card application that computes the total score.
> As you can see, I've used bind in calling accumulate and that
> seems to be ugly. So, I modified the code as follows:

Seems fine to me, but it's your code, so your opinion's the important
one.

> So, what I want to do is write a function get_score that successfuly
> compiles and run the following:
>
> total = accumulate(subjects.begin(), subjects.end(), 0, get_score(_1)
+
> get_score(_2));
>
> I've tried my best only to fail. Could anybody write get_score
functions
> for me?

You're motivation is unclear. The usual reason to use Boost.Lambda is
that you want to define all of the logic of the algorithm at the call
site, rather than having auxiliary definitions elsewhere. If you're
going to have some part of the algorithm get its own named definition,
then it's simpler just to use a regular function or function object.
Then everything is quite simple:

total = accumulate(subjects.begin(), subjects.end(), 0,
accumulate_scores);

This assumes that accumulate_scores is something like:

int accumulate_scores(int a, pair<char const*, int> const& b)
{ return a + b.second; }

If you really do want to write "total = accumulate(subjects.begin(),
subjects.end(), 0, get_score(_1) + get_score(_2));", you would need to
write two get_score() overloads, one that takes a
boost::lambda::placeholder1_type, and one that takes a
placeholder2_type. They could return types with an overloaded addition
operator that returned a boost::function of the appropriate type, or
they could return types equivalent to bind expressions. Although the
placeholder1_type overload would simply return its argument, the other
would return a long, complex, and I think unspecified type, though I
guess you could generate the type with boost::result_of.

Frankly, it sounds like far too much trouble; I'd take the simple route,
but it's your call.

-- 
Todd Greer

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net