Swap ()

Source: Internet
Author: User

I. Use third-party variables for variable value exchange

Note: There is no template in C, and there is a template in C ++

Template <class T>
Void swap (T & val1, T & val2)
{
T temp = val1;
Val1 = val2;
Val2 = temp;
}

Template <class T>
Void swap (T * V1, T * V2)
{
T temp = * V1;
* V1 = * V2;
* V2 = temp;
}

 

2. Do not use third-party Variables

Template <class T> void swap (T & V1, T & V2)

{

T temp = V1 + V2;

V1 = temp-V1;

V2 = temp-V1;

}

 

Note: method 1 consumes a variable memory space than method 2, and method 2 may overflow due to addition. 1st methods are used in the standard library.

 

Iii. Logical Operation Method

Note: At this time, t can only be int series and char Series

Template <class T>
Void swap1 (T & T1, T & T2)
{
T1 = T1 ^ T2;
T2 = T1 ^ T2;
T1 = T1 ^ T2;
}

The principle of this method (exclusive or operation ):

A ^ A = 0 (same as 0)

A ^ 1 = ~ A A ^ 0 =

A ^ B ^ c satisfies the exchange law and combination Law

 

In summary, the logic operation method is relatively less readable, but does not consume the memory space of the variable or overflow, but can only be used for int and char series.

The 1st method is better than the 2nd method, because it does not overflow, and the consumption of a memory variable space is not worth mentioning in common engineering applications.

Swap ()

Contact Us

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.