Sample Analysis of template and STL in C++
This article mainly introduces the C++ template and STL example analysis, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
I. template
For an exchange function, although C++ supports function overloading, we can give multiple exchange functions the same name:
Void Swap (int& left, int& right) {int temp = left; left = right; right = temp;} void Swap (double& left, double& right) {double temp = left; left = right; right = temp;}
But there are still some shortcomings, for example, if we want to exchange other types, such as char or class types, we still have to write another exchange function, so that other types of exchange functions are not reused, which greatly reduces the efficiency.
Therefore, C++ introduces the concept of template, through which a code can exchange different data.
Templates, in fact, tell the compiler a mold that the compiler uses to generate code according to different types.
1.1. Function template
* * generic programming: * * previously, functions were for a specific type (such as int,char), while generics were for a wide range of types. Templates are the foundation of generic programming.
So the parameter of the function template is not a specific type, and the specific type can only be determined when it is called.
Its syntax is:
/ / you can use typename to define the template parameter T, or you can use classtemplate to return the value type function name (with the parameter list specified by the generic type) {}
Take the exchange function as an example:
Templatevoid Swap (T & left, T & right) {T temp = left; left = right; right = temp;} int main () {int a = 10, b = 20; double c = 1.1, d = 2.2; Swap (a, b); Swap (c, d); cout