Junior task – sum of integers in vector

Assume that we have vector of integers ie.

and we want to write function which will sum up all its elements.

In which cases it will work?

Middle task – sum of elements in vector no matter what type

Let’s make it more generic and accept also other types than integers – let’s make it template, right?

In which cases it will work?

sum({1,4,7,9,3,4,5}) does not work because compiler is unable to deduce type of initializer_list because braced initializer_list has no type. We can make it work by preparing overloading for our function taking std::initializer_list .

and…

Unfortunately we have some nasty code duplication – let’s remove it.

OK, better and works as expected.

Let’s go further and try to make it even more generic – let it take any container.

Senior task – sum of elements in container

We would like to have function like

but we have missing definition of T – how we can deduce it? For STL containers we can use value_type attribute

It works for all previous cases:

so let’s try to use it with c-arrays ie.

We have to change code to use iterator_traits which is created to handle value_type and free functions std::begin()/std::end() for taking begin and end of container.

We can make this code little better by using additional using statement.

Now our function can handle all standard container types and c-arrays.

Expert question

Can we integrate std::initializer_list  version with Container  one?

 

About 

Service Delivery Manager and Scrum Master at Sii Poland company.

Since 2007 C++ enthusiast. C++11/14 evangelist - learn modern ways of developing in C++. Teaching TDD and agile way of coding.

  • googleplus
  • linkedin
  • twitter

4 comments on “Generic function which sum up elements from given container

  • Hi,

    I think that this line could be problematic:

    it works on assumption that default construcor initializes items with default value … but it might not allways be true.
    You could use code like that to avoid it:

      • Possible solution could be something like that:

        But the code branching here is imho nasty – kinda overkill. And there is still a case when it doesn’t work: empty container of type without default constructor.

        • OK, but if you anyway need default constructed value_type_t we could back to previous implementation

          right?

Leave a Reply