What are the differences between swap in C++ and Python?

老子叫甜甜 提交于 2019-12-20 03:22:04

问题


About swap, in C++, we can swap two by std::swap(x, y);. x and y are passed into swap as reference.

But in Python, can we also write a swap function which can do the swap the same way as in C++? The Python version of swap I implemented is kinda stupid:

def swap_in_python(x, y):
    return y, x

#so when swapping a and b, I usually do it like this
a, b = swap_in_python(a, b)

This is really cumbersome, but we can't pass reference or pointer as what we can do in C++, right?

EDIT:

Is there any other way not employing assignment(not using =)?


回答1:


Actually, in Python, it's much more elegant:

(a,b) = (b,a)

You don't have to call a function at all. And, yes, as per the comments, the parentheses are unnecessary here. I still prefer them since I believe they make the intent clearer.


Following edit:

Is there any other way not employing assignment (not using =)?

Possibly, though I don't know of one, and I can't imagine it would be simpler or more readable than the basic way shown above. If you're looking for a more complicated way of doing things that can be done simply, might I suggest that you're in the wrong mindset? :-)




回答2:


I don't believe that it is possible to simply implement the equivalent of C++'s swap in Python.

This is due to the fundamental differences between the C++ object model and the Python object model. In python all variables reference objects. With the swap that you have implemented, all that happens is the the objects referred to by the two variables are exchanged. The objects themselves are untouched so nothing referring to the existing objects will see any change.

In C++'s std::swap, the values of the two objects are exchanged so any expression denoting either of the objects being swapped will see the changes.

>>> c = [ "hello", "world" ]
>>> d = []
>>> a = c
>>> b = d
>>> a, b = swap_in_python(a, b)
>>> c
['hello', 'world']
>>> d
[]
>>>

vs

std::list<std::string> c, d;
c.push_back("hello");
c.push_back("world");
std::list<std::string> &a = c, &b = d;
std::swap( a, b ); // c is empty, d is "hello", "world"



回答3:


Python passes by pointer.

Simpler swap:

x, y = y, x



回答4:


You could just directly write

a, b = (b, a)


来源:https://stackoverflow.com/questions/7642909/what-are-the-differences-between-swap-in-c-and-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!