example2_custom_swap_functions.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <utility>
#include <iostream>
#include <vector>

class MyClass {
public:
    MyClass(int val) : value(val) {}
    int getValue() const { return value; }

    // Custom swap function
    friend void swap(MyClass& a, MyClass& b) noexcept {
        std::cout << "Custom swap called" << std::endl;
        std::swap(a.value, b.value);
    }

private:
    int value;
};

int main() {
    int a = 5, b = 10;
    std::cout << "Before swap: a = " << a << ", b = " << b << std::endl;
    std::swap(a, b);
    std::cout << "After swap: a = " << a << ", b = " << b << std::endl;

    std::vector<int> vec1 = {1, 2, 3};
    std::vector<int> vec2 = {4, 5, 6};
    std::cout << "Before swap: vec1[0] = " << vec1[0] << ", vec2[0] = " << vec2[0] << std::endl;
    std::swap(vec1, vec2);
    std::cout << "After swap: vec1[0] = " << vec1[0] << ", vec2[0] = " << vec2[0] << std::endl;

    MyClass obj1(100), obj2(200);
    std::cout << "Before swap: obj1 = " << obj1.getValue() << ", obj2 = " << obj2.getValue() << std::endl;
    std::swap(obj1, obj2);
    std::cout << "After swap: obj1 = " << obj1.getValue() << ", obj2 = " << obj2.getValue() << std::endl;

    return 0;
}
Back to utility