In article <11**********************@z14g2000cwz.googlegroups .com>,

"cesco" <fd**********@gmail.com> wrote:

I have a set of pairs defined as follow:

set< pair<UserEquipment*, double> > numberOfFreqSlotsToAdd;

and I need to iterate through all the elements of the set in order

accumulate the second field of the pair (that is double). Is there any

way I can use the algorithm accumulate to accomplish this?

The following line of code

double unit = accumulate( numberOfFreqSlotsToAdd.begin(),

numberOfFreqSlotsToAdd.end(), 0.0);

of course, won't work. Can you suggest anything similar using the

algorithm accumulate?

I gave an answer to this in comp.learn.c-c++. Here I will give several

answers:

class Object { };

int main() {

typedef std::set<std::pair<Object*, double> > MySet;

MySet mySet;

double unit = accumulate(mySet.begin(), mySet.end(), 0.0,

plus_second<MySet::value_type>() );

}

The 'plus_second' functor is defined as follows:

template <typename Pair>

struct plus_second :

std::binary_function<typename Pair::second_type, Pair,

typename Pair::second_type>

{

typename Pair::second_type operator()(

const typename Pair::second_type& x, const Pair& y ) const

{

return x + y.second;

}

};

Or something slightly more generic:

class Object { };

int main() {

typedef std::set<std::pair<Object*, double> > MySet;

MySet mySet;

double unit = accumulate(mySet.begin(), mySet.end(), 0.0,

apply_to_second<std::plus<double>, MySet::value_type>());

}

Which uses something like (though I can't say I like the name much:)

template < typename Op, typename Pair >

class apply_to_second : std::binary_function<

typename Pair::second_type, Pair, typename Pair::second_type >

{

Op fn;

public:

typename Pair::second_type operator()( const typename

Pair::second_type& x, const Pair& y ) const

{

return fn( x, y.second );

}

};

Whether you use one of the above, the one I gave in the other group, or

the simplest one:

class Object { };

typedef std::set<std::pair<Object*, double> > MySet;

double fn(double x, const MySet::value_type& y)

{

return x + y.second;

}

int main()

{

MySet mySet;

double unit = accumulate(mySet.begin(), mySet.end(), 0.0,

ptr_fun(&fn));

}

Is up to you. I'll leave you with the XP mantra, "use the simplest thing

that works, refactor mercilessly."

--

Magic depends on tradition and belief. It does not welcome observation,

nor does it profit by experiment. On the other hand, science is based

on experience; it is open to correction by observation and experiment.