Reputation: 1
#include <iostream>
#include <array>
using namespace std;
template<class InputIterator>
typename iterator_traits<InputIterator>::value_type
sumRange(InputIterator first, InputIterator last) {
// ignore validate [start, last)
typedef typename __iterator_traits<InputIterator>::value_type value_type;
value_type sum = *first++;
while (first != last) {
sum = sum + *first++;
}
return sum;
}
int main() {
array<int, 3> a{4, 5, 6};
cout << sumRange(a.begin(), a.end()) << endl;
return 0;
}
why the function sumRange
can not apply to built-in type such as int*
?
But the STL algorithm accumulate
work.
The error information is:
main.cpp:29:67: error: no type named 'value_type' in 'struct std::__iterator_traits<int*, void>'
typedef typename __iterator_traits<InputIterator>::value_type value_type;
Upvotes: 0
Views: 49
Reputation: 10880
For built-in types such as int[]
, you need to use std::begin(a)
and std::end(a)
on these types, also - as NathanOliver wrote - std::iterator_traits<>
instead of the implementation detail __iterator_traits<>
.
std::begin()
and std::end()
works for std containers as well (in which case, it delegates to the member functions begin()
and end()
, respectively), so these are more generic and thus preferred. It's also what range-based for
uses.
Upvotes: 2