I. Use third-party variables for variable value exchange
Note: There is no template in C, and there is a template in C ++
Template <class T>
Void swap (T & val1, T & val2)
{
T temp = val1;
Val1 = val2;
Val2 = temp;
}
Template <class T>
Void swap (T * V1, T * V2)
{
T temp = * V1;
* V1 = * V2;
* V2 = temp;
}
2. Do not use third-party Variables
Template <class T> void swap (T & V1, T & V2)
{
T temp = V1 + V2;
V1 = temp-V1;
V2 = temp-V1;
}
Note: method 1 consumes a variable memory space than method 2, and method 2 may overflow due to addition. 1st methods are used in the standard library.
Iii. Logical Operation Method
Note: At this time, t can only be int series and char Series
Template <class T>
Void swap1 (T & T1, T & T2)
{
T1 = T1 ^ T2;
T2 = T1 ^ T2;
T1 = T1 ^ T2;
}
The principle of this method (exclusive or operation ):
A ^ A = 0 (same as 0)
A ^ 1 = ~ A A ^ 0 =
A ^ B ^ c satisfies the exchange law and combination Law
In summary, the logic operation method is relatively less readable, but does not consume the memory space of the variable or overflow, but can only be used for int and char series.
The 1st method is better than the 2nd method, because it does not overflow, and the consumption of a memory variable space is not worth mentioning in common engineering applications.
Swap ()