Function Template

Hello.

I have to write a template for compareTwoArrays function. The function gets 2 same-sized arrays of type T and returns:

-1 if second array contains min/max number
0 if both arrays contain min/max number
1 if first array contains min/max number.

Template is of bool type:
- false: we are searching an array with minimum numbet
- true: we are searching an array with maximum number

Example:

1
2
3
4
int p1[]= {-11, 21, 3, 14, 7};
int p2[]= {1, 12, 31, -4, 3};
cout << "Minimum = " << compareTwoArrays<false>(p1, p2, 5) << endl // returns 1; 
cout << "Maximum =" << compareTwoArrays<true>(p1, p2, 5) << endl; // returns -1  


I tried to solve this, but I'm not sure how to do it.

Here's my "code":

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
template < typename T1, typename T2 >
bool compareTwoArrays (T2* array1, T2* array2, int array_size) {
  T2 max1;
  T2 max2;
  T2 min1;
  T2 min2;
  
  if (T1 == true) {
  
  for (int i = 0; i < arraysize; i++) {
    if (array1[i] < array1[i + 1]) {
      max1 = array1[i+1];
    }
  }
  
  for (int i = 0; i < arraysize; i++) {
    if (array2[i] < array2[i + 1]) {
      max2 = array2[i+1];
    }
  }
  
  if (max1 > max2) {
    return 1;
  }
  
  if (max1 < max2) {
    return -1;
  }
  
  if (max1 == max2) {
    return 0;
  }
 }
 
 else {
   for (int i = 0; i < arraysize; i++) {
    if (array1[i] > array1[i + 1]) {
      min1 = array1[i+1];
    }
  }
  
  for (int i = 0; i < arraysize; i++) {
    if (array2[i] > array2[i + 1]) {
      min2 = array2[i+1];
    }
  }
  
  if (min1 > min2) {
    return 1;
  }
  
  if (min1 < min2) {
    return -1;
  }
  
  if (min1 == min2) {
    return 0;
  }
 } 
}
Last edited on
I'm not sure if I quite understand what you're trying to do, but if you want the template parameter T1:
typename T1
to be a bool, then you must do this:
bool T1
instead.
Last edited on
Topic archived. No new replies allowed.