Array to Template Class help

I'm trying to make an array that takes a group of numbers and finds the largest number into a template class. I find myself struggling to understand how to go about doing it and any information I've found isn't helping me any.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
template<class TYPE>
void Integers(TYPE data)
{
	int integers[] = {4, 25, 32, 85, 150, 12, 98, 200};
	int i = 0;
	int Max=integers[0];

	for (i=1; i < 8; i++)
	{
		if(integers[i] > Max)
		{
			Max=integers[i];
		}
	}
	cout << "Biggest Number: " << Max;
	cout << "                " << endl;
	system("Pause");
	return 0;
	
}


I'm sure I'm going about it all wrong, but I'm not sure as to get it so that it will accept the arrays input.

@Paul

I am going to ask you some questions to help you figure out some concepts.

What is the main idea behind using templates? Or, why would you use a template function as opposed to a normal function?

Can you think of a better name for your function?

Why is the variable data not used in the function? This is related to the first question.

What is the value of the subscript for the numbers 4 and 200 in your array? And what is the value of integers[8] ?

Having answered the previous question, can you see how there are 2 problems on line 8? Hint : what if the first value in the array was 1000? Related in part to the value of integers[8]

On line 16, which variable needs to be output?

On line 17, can you think of a reason for NOT putting that system command there? Apart from the idea that using system is a bad idea, I mean the placement of it in the flow of the program.

Can you see a conflict between line 18 and line 2?

Hope this helps a bit. Cheers :+)
Last edited on
As you have it now, this template function does not need to be a template, as class TYPE is not used and the parameter TYPE data is not used. Also the template function does a return 0 while it is typed to return void.

So one possible set of improvements would be to remove the line:

template<class TYPE>

and change the name and parameters of the function to something like:

void printMaxInt()

or use the template by using it with different types, and calling it with the arrays:

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
29
#include <iostream>

template<class TYPE>
TYPE MaxValue(const TYPE values[], unsigned length)
{
  TYPE Max=values[0];
  
  for (unsigned i = 1; i < length; ++i)
  {
    if (values[i] > Max)
    {
      Max = values[i];
    }
  }
  return Max;
}

using namespace std;

int main()
{
  int integers[] = {4, 25, 32, 85, 150, 12, 98, 200};
  cout << "Biggest integer: " << MaxValue<int>(integers, 8) << endl;

  double dvalues[] = { -1.0, 0.0, 1.2 };
  cout << "Biggest double: " << MaxValue<double>(dvalues, 3) << endl;

  return 0;
}


Biggest integer: 200
Biggest double: 1.2


Refer: http://www.cplusplus.com/reference/algorithm/max_element/
Topic archived. No new replies allowed.