3

C++ 一种交换两个数的思路 - mkckr0

 1 year ago
source link: https://www.cnblogs.com/mkckr0/p/17048133.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

C++ 一种交换两个数的思路

在 Lua 或者 Python 中可以使用多值赋值语句来交换两个数。例如:a, b = b, a。在 C++ 中有没有类似的操作?

先解析一下多值赋值的原理,a, b = b, a 等价于

t1, t2 = b, a
a, b = t1, t2

可以看到多值赋值还是用到了中间变量,而且还是两个。想到两个变量,可以联想到 C++ 中的 std::pair,可以用 std::make_pair(b, a) 构造中间变量,来完成上述第 1 条语句的功能。中间变量是 std::pair 类型。如何将 std::pair 的两个元素赋值给 a 和 b ? 可以利用 std::tie 对 std::pair 进行 unpack。示例代码如下:

#include <iostream>
#include <tuple>

int main()
{
    int a = 1, b = 2;
    std::tie(a, b) = std::make_pair(b, a);
    std::cout << a << " " << b << std::endl;
}

成功输出:

2 1

这种方法也和多值赋值一样可以适用于多个数的交换。例如让 a、b、c、d 四个数左循环交换一次(全部往左边挪一个位置)。示例代码如下:

#include <iostream>
#include <tuple>

int main()
{
    int a = 1, b = 2, c = 3, d = 4;
    std::tie(a, b, c, d) = std::make_tuple(b, c, d, a);
    std::cout << a << " " << b << " " << c << " " << d << std::endl;
}

成功输出:

2 3 4 1

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK