Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Hàm swap() trong C++


Hàm swap() hoán đổi giá trị hai biến. Không cần biến trung gian thứ ba.

Cú pháp:

void swap(int variable_name1, int variable_name2);

Nếu truyền bằng giá trị, giá trị hoán đổi cục bộ, biến gốc không đổi. Nên truyền bằng tham chiếu để hoán đổi tại chỗ.

Ví dụ 1 - Truyền giá trị

#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;
}

Kết quả

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

Ví dụ 2 - Truyền tham chiếu (hoán đổi thực sự)

#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;
}

Kết quả

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