Trying to create simple template sum of container
Sep 30, 2012 at 5:20pm UTC
I'm just trying to create a simple sum function template to find the sum of doubles within a container using STL. First I'm just trying to test this with a list, but I keep getting an error on line 28.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
#include <iterator>
#include <list>
#include <iostream>
using namespace std;
template <typename T>
double Sum(typename T& container)
{// sum of a container with doubles
typename T::const_iterator iterator_begin = container.begin();
typename T::const_iterator iterator_end = container.end();
double my_sum = 0;
for (iterator_begin; iterator_begin != iterator_end; iterator_begin++)
my_sum += iterator_begin->second; // this is line 28
return my_sum;
}
int main()
{
list<double > test_list(10,5.1); // create a list of size 10 with values 5.1
cout << Sum(test_list) << endl;
return 0;
}
I get two compiler errors:
c:\users...\iterators.cpp(28): error C2839: invalid return type 'const double *' for overloaded 'operator ->'
c:\users...\iterators.cpp(28): error C2039: 'second' : is not a member of 'std::_List_const_iterator<_Mylist>'
Even if I change from const_iterator to iterator, I still receive a similar error:
error C2839: invalid return type 'double *' for overloaded 'operator ->'
Am I using the pointers wrong here or something? Thanks!
Sep 30, 2012 at 7:07pm UTC
Error was that second is not a member of list. Rather, it's a member of map.
Topic archived. No new replies allowed.