Choose from
Ken98091 BLOG
Exchange 2 variables and temporary variables first to see the most common exchange method Template void swap1 (t & a, t & b) {t temp = a; a = b; b = Temp;} template void swap2 (t & a, t & b) {a = a ^ b; b = a ^ b; a = a ^ b;} template void swap3 (t & a, t & b) { A = a b; b = a - b; A = a - b;} In SWAP1, it can be seen that the code is very concise, and it is afraid of beginners, it can look at its role, but because it Used a temporary variable, this means more memory, although only the stack space SWAP2, the smartly use of the different or operations to reach the destination code of the exchange, but only three lines, but not a eye to see it. The role, this is a lot of swap1, but it has saved a temporary variable. Although it is just a temporary variable - the memory occupied by the occupation may be rare, but as a Yellow Ezon, a Chinese child, province It's our virtue !!! Swap3 is similar to swap2, just turned from different or operations into a decrease. The province is our virtue, then, on this basis, it is more reflected in the spirit of the Chinese nation. Home !!! But please take a look at our function declaration, there is a template in front of it, it's right, this is a function template, this is C Int i, J; swapx (i, j); No matter which one, you can pass ^ _ ^ ps: swap3 does not need to consider overflow problems, why? Do you want to see Float F1, F2; Swapx (F1, F2); how, do you have trouble when compiling? A Struct R {Long A; Long B;} Rect R1, R2; SWAPX (R1, R2); this time is more trouble, only swap1 can come here, draw a conclusion: from "Function Mode" To talk about SWAP1 is qualified, because SWAP2 and swap3 can't talk through all types, the temporary variable becomes necessary !! Sure enough ??? Otherwise !!! The following is the perfect solution code Never want to say more ,,, Template Void Swapex (T & A, T & B) {__ASM {Mov ECX, Size T Mov ESI, A MOV EDI, B Next: MOV Al, [ESI] MOV AH, [ED I] MOV [EDI], Al Mov [ESI], AH INC ESI Inc Edi loop next}} No matter what type or class, you can exchange it, and the speed is the fastest !!!