Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass iterator as a function parameter

I try to write a function, which will sum the elements of a container. This container can be Vector, List, Queue, etc... That's why I tried templates.

Unfortunately I get this error:

'C' is not a template

Source:

#include <iostream>
#include <vector>

using namespace std;

template<class C, typename T>
T sum( C<T>::iterator begin, C<T>::iterator end ) {
    T s = null;

    for (C<T>::iterator it = begin; it != end; it++) {
        s += *it;
    }

    return s;
}

int main()
{
    vector<int> v = {5, 9, 0, 11};

    cout << sum(v.begin(), v.end()) << endl;

    return 0;
}

What do I wrong? How should I fix it?

like image 271
Iter Ator Avatar asked Nov 27 '13 14:11

Iter Ator


1 Answers

You could express the whole thing in terms of a iterator type, and use iterator_traits to get the value_type:

#include <iterator>

template<typename Iterator>
typename std::iterator_traits<Iterator>::value_type 
sum(Iterator begin, Iterator end)
{
  using value_type = typename std::iterator_traits<Iterator>::value_type;
  value_type s = value_type();
  for (Iterator it = begin; it != end; it++) {
    s += *it;
  }
  return s;
}

In real life, use std::accumulate:

int sum = std::accumulate(v.begin(), v.end(), 0);
like image 50
juanchopanza Avatar answered Sep 22 '22 13:09

juanchopanza