# The swap algorithm of type int, char*, string,

Source: Internet
Author: User

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,

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.