accumulate instead of for-loop

J

James Kanze

Let v be:
vector<pair<string, size_t> > v;
sum = 0;
for (size_t k = 0; k < v.size(); k++)
{
sum += v[k].second;
}
Is it possible to compute sum using std::accumulate (i.e. not using
for-loop)?

I'm pretty sure that Boost iterators have something which
supports this, probably right out of the box, but at the very
least transform_iteratror in collaboration with bind will do the
trick.
 
J

Jerry Coffin

Let v be:

vector<pair<string, size_t> > v;

sum = 0;
for (size_t k = 0; k < v.size(); k++)
{
sum += v[k].second;
}

Is it possible to compute sum using std::accumulate (i.e. not using
for-loop)?

Yes, though it's open to question whether it's really any improvement:

typedef std::pair<std::string, size_t> p;

struct add_second : std::binary_function<size_t, size_t, p> {
size_t operator()(size_t a, p const &b) { return a+b.second; }
};

size_t sum = std::accumulate(v.begin(), v.end(), 0, add_second());

Using Boost.lambda, I believe you should also be able to do something
like this:

size_t sum=std::accumulate(v.begin(), v.end(), 0, var(_1).second);
 
M

Michael DOUBEZ

Alex Vinokur a écrit :
Let v be:

vector<pair<string, size_t> > v;

sum = 0;
for (size_t k = 0; k < v.size(); k++)
{
sum += v[k].second;
}


Is it possible to compute sum using std::accumulate (i.e. not using
for-loop)?

You can use a functor to project on the second element of the pair:

template<class Pair>
class pair_get2nd
{
typedef Pair argument_type;
typedef typename Pair::second_type result_type;

const result_type& operator()(const argument_type& t)const
{
return t.second;
}
};

And then

typedef vector<pair<string, size_t> > my_vector;
my_vector v;
sum = std::accumulate(v.begin(), v.end(),0,
pair_get2nd<my_vector::value_type>());


Michael
 

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

Members online

No members online now.

Forum statistics

Threads
473,968
Messages
2,570,150
Members
46,697
Latest member
AugustNabo

Latest Threads

Top