Template confusion

Started working with templates, don't fully understand things. What I think I'm trying to do is to make a template that compares 5 array elements of a yet to be determined type and returns the largest element. Currently when I run as is it returns Integer max is: 1606416160 Decimal max is: 2.81006e+101. Which I don't really get. It makes me pass the arrays in by address which I'm not sure why. Do I need to be using pointers or is there something else I'm missing? Any help welcomed.

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
  template <class myType>
myType GetMax (myType a[5])
{
    myType max = a[0];
    for (int i = 0; i < 5; i++)
    {
        if (a[i] > max)
        {
            max = a[i];
        }
    }
    return (max);
}

int main(int argc, const char * argv[])
{
    int a[5] = {0,1,2,3,4};
    double b[5] = {1.1,2.1,3.1,1.4,2.5};
    int max1;
    double max2;
    max1 = GetMax<int>(&a[5]);
    max2 = GetMax<double>(&b[5]);
    cout << "Integer max is: " << max1 << endl << "Decimal max is: " << max2 << endl;
    return 0;
}



edit: okay I've figured out that passing the address is bad but I'm not sure how to fix it?
Last edited on
Lines 21 and 22 are incorrect - instead pf passing the array from the beginning, you're passing the array from the element after the last element. This results in you reading random memory.

Just write it the simple way:
21
22
    max1 = GetMax(a);
    max2 = GetMax(b);
Last edited on
Thank you I'm not sure what I was thinking that works perfectly.
Topic archived. No new replies allowed.