1. Two integers, do not use intermediate variables to exchange their values:
int& Intswap (intint& b) { ^= A; ^= b; ^= A; return b;}
2.c++ Two string Exchange strings
string & Strswap (stringstring & b) { a=a.append (b); b= A.substr (0, A.length ()-b.length ()); A=a.substr (b.length (), a.length ()); return b;}
3.char* String Exchange value // do not use dynamic memory, perform 1000w times time consuming 2s, use dynamic memory time consuming 3s.
//do not use dynamic memory:Char* CSWAP (CharAChar*b) { inti =0; intAlen = strlen (a), blen=strlen (b); Strcat (A, b); for(; I < alen;i++) {B[i]=A[i]; } B[i]=' /'; for(i =0; I < blen;i++) {A[i]= A[alen +i]; } A[i]=' /'; returnA;}//using dynamic memoryintCharswap (Char*a,Char*b) { Char* temp=NULL;
int n = strlen (a) > strlen (b)? (Strlen (a) +1): (strlen (b) +1); Temp= (Char*)malloc(n *sizeof(Char)); strcpy (temp, a); strcpy (A, b); strcpy (b, temp); Free(temp); return 0;}
Function call:
1#include <iostream>2#include <string.h>3 using namespacestd;4 intMainvoid)5 {6 clock_t start, finish;7 Chara[ -] ="Hellohellohellohellohellohellohellohellohellohello";8 Charb[ -] ="Hihihihihihihihihihihi";9 intAlen =strlen (a);Ten intBlen =strlen (b); OneStart =clock (); A for(inti =0; I <9999999;++i) - { - Cswap (A, b); the //Charswap (A, b); - } -finish =clock (); - Doublet = (Finish-start)/clocks_per_sec; +cout <<"Costs:"<< T <<"s"<<Endl; -cout <<"a="<< a <<Endl; +cout <<"b="<< b <<Endl; A return 0; at}
Execution Result:
The swap algorithm of type int, char*, string,