gpt4 book ai didi

c++ - 交换 x 和 y 的值

转载 作者:太空宇宙 更新时间:2023-11-04 16:00:23 25 4
gpt4 key购买 nike

如何更改这段代码中 x 和 y 的值?

当我尝试通过 x=y, y=x; 执行此操作时,它会将其更改为相同的数字。

我该怎么做?

如何为 3 个值(x y z)执行此操作?

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

我之前试过这段代码,但它没有按照我想要的方式工作。

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

最佳答案

这是因为你先设置了x的值,然后将该值复制到 y .有一个名为 std::swap 的标准库函数,应该可以完成这项工作。

你可以看到它的一个例子here .

std::swap在 header 中定义 <algorithm>在 C++11 之前和 <utility> 中从 C++11 开始。所以确保你#include正确的标题。

使用 std::swap 的好处在 C++11 中,与将值复制到第三个临时变量相反,是 std::swap使用 std::move从而不会创建额外的拷贝。


对于三个数字,您必须像这样进行自己的实现:

#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

关于c++ - 交换 x 和 y 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45688657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com