1.俩整数,不使用中间变量交换其值:
int& intswap(int& a, int& b) { b ^= a; a ^= b; b ^= a; return b; }
2.C++中俩string交换字符串
string & strswap(string & a, string & b) { a=a.append(b); b= a.substr(0,a.length()-b.length()); a=a.substr(b.length(),a.length()); return b; }
3.char*字符串交换值//不使用动态内存,执行1000w次耗时2s,使用动态内存耗时3s。
//不使用动态内存: char* cswap(char* a, char* b) { int i = 0; int alen = strlen(a),blen= strlen(b); strcat(a, b); for (;i < alen;i++) { b[i] = a[i]; } b[i] = ‘\0‘; for (i = 0;i < blen;i++) { a[i] = a[alen + i]; } a[i] = ‘\0‘; return a; } // 使用动态内存 int charswap(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; }
函数调用:
1 #include<iostream> 2 #include<string.h> 3 using namespace std; 4 int main(void) 5 { 6 clock_t start, finish; 7 char a[100] ="hellohellohellohellohellohellohellohellohellohello"; 8 char b[60] = "hihihihihihihihihihihi"; 9 int alen = strlen(a); 10 int blen = strlen(b); 11 start = clock(); 12 for (int i = 0;i < 9999999;++i) 13 { 14 cswap(a, b); 15 //charswap(a, b); 16 } 17 finish = clock(); 18 double t = (finish - start)/CLOCKS_PER_SEC ; 19 cout << "costs: " << t << "s" << endl; 20 cout << "a= " << a << endl; 21 cout << "b= " << b << endl; 22 return 0; 23 }
执行结果:
时间: 2024-10-28 23:51:45