int型、char*、string、的swap算法

1.倆整數,不使用中間變量交換其值:ios

int& intswap(int& a, int& b)
{
    b ^= a;
    a ^= b;
    b ^= a;
    return b;
}

2.C++中倆string交換字符串app

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; }

函數調用:spa

 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 }

 

執行結果:code

相關文章
相關標籤/搜索