c++ - Swap values of x and y -


how can change values of x , y in code?

when try x=y, y=x; changes same numbers.

how can this?

how can 3 values (x y z)?

#include <iostream> using namespace std; int main() {     int x=4;     int y=6;     cout<<x<<y;     return 0; } 

i tried code before isn't working way want it.

#include <iostream> using namespace std; int main() {     int x=4;     int y=6;     x=y,y=x;     cout<<x<<y;     return 0; } 

this because first set x's value , copy value y. there standard library function called std::swap, should job.

you can see exapmle of here.

std::swap defined in header <algorithm> before c++11 , in <utility> since c++11. make sure #include correct header.

the benefit of using std::swap in c++11 opposed having third temporary variable copy value into, std::swap uses std::move , thereby creates no additional copies.


for 3 numbers you'll have make own implementation this:

#include <iostream>  int main() {     int x{5}, y{3}, z{2};      int temp{std::move(x)};     x = std::move(y);     y = std::move(z);     z = std::move(temp);      std::cout << x << ' ' << y << ' ' << z << '\n';      return 0;  } 

ideone


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -