Problem: Write a function to find the maximum value of an integer array.
In general writing, two parameters are required. One parameter indicates the starting address of the array and the other parameter indicates the size of the array. But the more direct idea is that the size of the array should be an attribute of the array itself. Every time you use the min function, you must tell it the size, which is obviously a cumbersome task. Fortunately, the C ++ template mechanism provides me with a better implementation method. First look at the Code:
Template <typename type, int size>
Type min (const type (& r_array) [size])
...{
Type min_val = r_array [0];
For (INT I = 1; I <size; ++ I)
If (r_array [I] <min_val)
Min_val = r_array [I];
Return min_val;
}
Template parameters are initialized during compilation, so the size is known. Surprisingly, the usage of this function is as follows:
Int main ()...{
Int Ia [] =... {10, 7, 14,3, 25 };
Double da [6] =... {10.2, 7.1, 14.5, 3.2, 25.0, 16.8 };
Cout <min (IA) <Endl;
Cout <min (DA) <Endl;
System ("pause ");
Return 0;
}
We can see that the size of the array is indeed part of the array type, otherwise min cannot obtain the size at all. Unlike the C language, the array name is regarded as a pointer.