C ++ templates and Arrays

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.