Basic memo: Use of function templates in Arrays

Source: Internet
Author: User

Function templates are widely used in actual programs because of their own characteristics: After defining a function body, you can call them multiple times for instantiation.
Example:
[Cpp]
# Include <iostream>
Using namespace std;
Template <typename T, int size> // function template parameters, including type parameter T and value parameter size
Int find (T (& array) [size], T var) // defines the search function: find the element var in the T-type array
{
For (int I = 0; I <size; I ++)
{
If (var = array [I])
Return I + 1;
}
Return-1;
}

Int main ()
{
Int a [5] = {3, 2, 4, 5, 1 };
Double B [6] = {1.0, 2.1, 3.2, 4.3, 5.4, 6.5 };
Cout <"position of integer 1:" <find (a, 1) <endl;
Cout <"floating point 4.3 position:" <find (B, 4.3) <endl;
System ("pause ");
}

Output:
Note that the operator & is used before the array. This is the address operator. You can pass the first address of the array in the real parameter.

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.