template beginner with vector

want to make a function to add all value in a vector regardless of type.just not able to find the mistake in this following code. any help would be appreciated!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  #include <iostream>
#include <vector>
using namespace std;

template<typename type>
type sum(vector<type> vec)
{
    type updated_sum=0;
    for(vector<type>::iterator itr=vec.begin(),  end=vec.end();itr!=end;++itr)
    {
        updated_sum+=*itr;
    }
    cout<<"The sum is: ";
    return updated_sum;
}

int main()
{
    vector<int> vec;
    vec.push_back(5);
    vec.push_back(6);
    sum<int> (vec);
}
You are never printing updated_sum to the screen, you are returning it (and then not using that value). Otherwise it seems to work?

Also just as a reminder there is a function to do this already.
http://www.cplusplus.com/reference/numeric/accumulate/
@James2250 i got that i didn't print the value part but the function still doesn't work. every error is shown in the line where I iterate in the vector(line 9 above). can u see what the mistake is?
also, i didn't know that there is a function already for this but i am making this function as a practice exercise for template. so i need to write this function anyway.
Does it work if you replace line 9 with the following?
 
for(vector<type>::iterator itr=vec.begin();itr!=vec.end();++itr)

You need to tell the compiler that vector<type>::iterator is a type by using the typename keyword.

for (typename vector<type>::iterator itr=vec.begin(), end=vec.end();itr!=end;++itr)
@peter87 it did work. thanks.
@shadowmouse it's not very different from what i did
Last edited on
Topic archived. No new replies allowed.