Swap in c C + + C # Java

Source: Internet
Author: User

Write a function to exchange the values of two variables.

C:

Implementation of the error:

void swap (intint  j) {   int t = i;    = J;    = t;}

Because the function parameter of C is passed as a value (pass by value), the parameter is copied when it is passed, so the value is exchanged in the function.

The right implementation:

Pointer version:

void swap (intint *j) {   int t = *i;    *i = *j;    *j = t;}

When a function is used to pass the address of a variable, such as Swap (&A,&B), the function swaps the value of two pointers, which is the value of two variables, so the interchange succeeds.

Pre-processing version:

#define Swap (type, I, j) {type T = i; i = j; j = t;}

The essence of preprocessing is text substitution (textual substitution).

The following code:

#define Swap (type, I, j) {type T = i; i = j; j = t;} int Main () {    int;    printf ("before swap. A:%d, B:%d\n", A, b);    Swap (int, A, b)    printf ("afterswap.  A:%d, B:%d\n", A, b);     return 0 ;}

The code after preprocessing is:

int Main () {    int;    printf ("before swap. A:%d, B:%d\n", A, b);      int t = A; A = b; b = T;}    printf ("afterswap.  A:%d, B:%d\n", A, b);     return 0 ;}

So the value of two variables can be exchanged correctly.

C++:

Mode one: Use pointers as in C language.
Mode two: Use "References" (&)

void swap (intint& j) {    int t = i;     = J;     = t;}

C + + 's function arguments use a reference (&), the value is passed by reference (pass by reference), the arguments in the function are not copied (if the class is passed the copy constructor is not called), so the value of the two variables can be correctly exchanged in the function.

C#:

Static void Swap<t> (refref  T rhs) {    T temp;     = LHS;     = RHS;     = temp;}

Do not forget the REF keyword, if not is not the correct exchange!

Java:

java.util.Collections;  Public Static void Swap (list<?> List,int i,int j)

Use the static method in the collection.

If you do not use an array collection, there is no simple function in Java to exchange the values of two variables. Unless you encapsulate it yourself:

//Myinteger:similar to Integer, but can change valueclassMyinteger {Private intX//Single data member    PublicMyinteger (intXIn) {x = XIn;}//Constructor    Public intGetValue () {returnX }//Retrieve value    Public voidInsertvalue (intXIn) {x = XIn;}//Insert} Public classSwapping {//Swap:pass references to Objects   Static voidSwap (Myinteger rwrap, Myinteger swrap) {//interchange values inside objects      intt =Rwrap.getvalue ();      Rwrap.insertvalue (Swrap.getvalue ());   Swrap.insertvalue (t); }    Public Static voidMain (string[] args) {intA = all, B = 47; System.out.println ("Before. A: "+ A +", B: "+b); Myinteger Awrap=NewMyinteger (a); Myinteger Bwrap=NewMyinteger (b);      Swap (Awrap, bwrap); A=Awrap.getvalue (); b=Bwrap.getvalue (); System.out.println ("After." A: "+ A +", B: "+b); }}

C # This is the same as Java, and the swap function does not work correctly if you do not use the REF keyword for the C # version.

While C # and Java can modify the value of a parameter through function parameters, this is a big difference from C + + references.

Look at the following function:

 Public voidTricky (Point arg1, point arg2) {arg1.x= 100; Arg1.y= 100; Point Temp=arg1; Arg1=arg2; Arg2=temp;}  Public Static voidmain (String [] args) {point pnt1=NewPoint (0,0); Point Pnt2=NewPoint (0,0); System.out.println ("X:" + pnt1.x + "Y:" +pnt1.y); System.out.println ("X:" + pnt2.x + "Y:" +pnt2.y); System.out.println (" ");    Tricky (Pnt1,pnt2); System.out.println ("X:" + pnt1.x + "Y:" +pnt1.y); System.out.println ("X:" + pnt2.x + "Y:" +pnt2.y);}

Execute this function and you will get the following output:

———————————————————-
x:0 y:0
x:0 y:0

x:100 y:100
x:0 y:0
———————————————————-

When Java passes an object to a function, two references point to the same object:

When passed to a function, there is at least two references to an object

Java replicates and passes the value of "reference", not the object. Therefore, the calculation of the object in the method will work, because the reference points to the original object. But because the reference to the object in the method is "copy," the object Exchange does not work. As shown, the swap action only works on the reference copy in the method, and does not affect references outside the method. So I'm sorry, after the method is called, it can't change the reference of the object outside the method. If you want to exchange an object reference outside the method, we should exchange the original reference instead of its copy.

Only the reference to the passed-in function is exchanged, but the original reference is not.

Reference:  

Http://www.cs.utsa.edu/~wagner/CS2213/swap/swap.html
Http://stackoverflow.com/questions/1363186/is-it-possible-to-write-swap-method-in-java
Http://www.importnew.com/3559.html

Swap in c C + + C # Java

Related Article

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.