C ++中的swap()函数

swap()函数用于交换两个数字。通过使用此函数,您不需要任何第三变量即可交换两个数字。

这是swap()C ++语言的语法,

void swap(int variable_name1, int variable_name2);

如果我们将值分配给变量或传递用户定义的值,它将交换变量的值,但变量的值在实际位置将保持不变。

这是swap()C ++语言的示例,

示例

#include <bits/stdc++.h>

using namespace std;

int main() {

   int x = 35, y = 75;

   printf("Value of x :%d",x);

   printf("\nValue of y :%d",y);

   swap(x, y);

   printf("\nAfter swapping, the values are: x = %d, y = %d", x, y);

   return 0;

}

输出结果

Value of x :35

Value of y :75

After swapping, the values are: x = 75, y = 35

最好通过引用将值传递给变量,它将在实际位置交换变量的值。

这是swap()C ++语言的另一个示例,

示例

#include <stdio.h>

void SwapValue(int &a, int &b) {

   int t = a;

   a = b;

   b = t;

}

int main() {

   int a, b;

   printf("Enter value of a : ");

   scanf("%d", &a);

   printf("\nEnter value of b : ");

   scanf("%d", &b);

   SwapValue(a, b);

   printf("\nAfter swapping, the values are: a = %d, b = %d", a, b);

   return 0;

}

输出结果

Enter value of a : 8

Enter value of b : 28

After swapping, the values are: a = 28, b = 8

以上是 C ++中的swap()函数 的全部内容, 来源链接: utcz.com/z/331078.html

回到顶部