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


    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] = '';
        for (i = 0;i < blen;i++)
        {
            a[i] = a[alen + i];
        }
        a[i] = '';
        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 }

    执行结果:

  • 相关阅读:
    看《环太平洋》归来
    在Fedora8上安装MySQL5.0.45的过程
    在Win7上安装MySql5.2遇到Write configuration file的解决
    每一个问题都是一把锁
    Fedora8上Apache Httpd与Tomcat6初集成
    在Fedora8上的Tomcat上deploy一个war
    在Fedora8上配置Tomcat6.0.37
    在Fedora8上配置Apache Httpd
    在Fedora8上安装jdk-7u25-linux-i586.rpm的步骤
    Java继承中的几道面试题
  • 原文地址:https://www.cnblogs.com/Burgess-Fan/p/7435295.html
Copyright © 2020-2023  润新知