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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With