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

本文介绍了C++中三种不同的值交换方法:整数交换、字符串交换及字符数组交换,并对比了使用动态内存分配与未使用动态内存分配时的效率。

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 }

 

执行结果:

转载于:https://www.cnblogs.com/Burgess-Fan/p/7435295.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值