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

前端 未结 4 1536
北荒
北荒 2021-01-21 20:50

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

But

4条回答
  •  孤街浪徒
    2021-01-21 21:26

    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? :-)

提交回复
热议问题