Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to sum the result of a member function for all elements in a container?

Let's say I have the following object:

struct Foo
{
    int size() { return 2; }
};

What's the best way (most maintainable, readable, etc.) to get the total size of all objects in a vector<Foo>? I'll post my solution but I'm interested in better ideas.

Update:

So far we have:

  • std::accumulate and a functor
  • std::accumulate and a lambda expression
  • plain ol' for-loop

Are there any other workable solutions? Can you make something maintainable using boost::bind or std::bind1st/2nd?

like image 755
Michael Kristofik Avatar asked Jul 08 '10 14:07

Michael Kristofik


People also ask

Which function can be used to find the sum of the vector container?

Which function can be used to find the sum of a vector container? Explanation: STL provides accumulate() function to find the sum of a vector.

How do you find the sum of all elements in a vector C++?

Sum up of all elements of a C++ vector can be very easily done by std::accumulate method. It is defined in <numeric> header. It accumulates all the values present specified in the vector to the specified sum.

How do you sum a vector element?

If A is a vector, then sum(A) returns the sum of the elements. If A is a matrix, then sum(A) returns a row vector containing the sum of each column. If A is a multidimensional array, then sum(A) operates along the first array dimension whose size does not equal 1, treating the elements as vectors.

What does accumulate function do in C++?

1) accumulate(): This function returns the sum of all the values lying in a range between [first, last) with the variable sum.


1 Answers

In addition to your own suggestion, if your compiler supports C++0x lambda expressions, you can use this shorter version:

std::vector<Foo> vf;

// do something to populate vf


int totalSize = std::accumulate(vf.begin(),
                                vf.end(),
                                0, 
                                [](int sum, const Foo& elem){ return sum + elem.size();});
like image 189
jalf Avatar answered Nov 01 '22 23:11

jalf