C++ 和 Python 中的交换有什么区别? [英] What are the differences between swap in C++ and Python?

查看:36
本文介绍了C++ 和 Python 中的交换有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于swap,在C++中,我们可以通过std::swap(x, y);来交换两个.xy 作为 reference 传递到 swap.

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

但是在 Python 中,我们是否也可以编写一个 swap 函数,它可以像在 C++ 中一样进行交换?我实现的 Python 版本的 swap 有点愚蠢:

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)

这确实很麻烦,但是我们不能像在C++中那样传递引用或指针,对吧?

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

有没有其他不使用赋值的方法(不使用=)?

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

推荐答案

实际上,在 Python 中,它要优雅得多:

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.

以下

有没有其他不使用赋值的方法(不使用=)?

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

这篇关于C++ 和 Python 中的交换有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆