💡 퀵 접속: cpp.kr/swap

swap

C++ 표준 라이브러리의 알고리즘으로, 두 값의 위치를 서로 바꿉니다. swap은 원본 값을 직접 수정하며, 두 값의 타입이 같아야 합니다. 기본 타입뿐만 아니라 사용자 정의 타입에 대해서도 사용할 수 있습니다.

기본 사용법

#include <iostream>
#include <algorithm>

int main() {
    int a = 5, b = 10;
    
    std::cout << "교환 전: a = " << a << ", b = " << b << std::endl;
    
    // 두 값 교환
    std::swap(a, b);
    
    std::cout << "교환 후: a = " << a << ", b = " << b << std::endl;
    
    return 0;
}

실행 결과:

교환 전: a = 5, b = 10
교환 후: a = 10, b = 5

문자열에서 사용

#include <iostream>
#include <string>
#include <algorithm>

int main() {
    std::string str1 = "Hello";
    std::string str2 = "World";
    
    std::cout << "교환 전: str1 = " << str1 << ", str2 = " << str2 << std::endl;
    
    // 두 문자열 교환
    std::swap(str1, str2);
    
    std::cout << "교환 후: str1 = " << str1 << ", str2 = " << str2 << std::endl;
    
    return 0;
}

실행 결과:

교환 전: str1 = Hello, str2 = World
교환 후: str1 = World, str2 = Hello

사용자 정의 타입에서 사용

#include <iostream>
#include <string>
#include <algorithm>

class Person {
    std::string name;
    int age;
public:
    Person(const std::string& n, int a) : name(n), age(a) {}
    
    void print() const {
        std::cout << name << " (" << age << "세)" << std::endl;
    }
};

int main() {
    Person p1("Alice", 20);
    Person p2("Bob", 30);
    
    std::cout << "교환 전:" << std::endl;
    std::cout << "p1: ";
    p1.print();
    std::cout << "p2: ";
    p2.print();
    
    // 두 객체 교환
    std::swap(p1, p2);
    
    std::cout << "\n교환 후:" << std::endl;
    std::cout << "p1: ";
    p1.print();
    std::cout << "p2: ";
    p2.print();
    
    return 0;
}

실행 결과:

교환 전:
p1: Alice (20세)
p2: Bob (30세)

교환 후:
p1: Bob (30세)
p2: Alice (20세)

참고사항

  • swap은 algorithm 헤더에 정의되어 있습니다.
  • 원본 값을 직접 수정합니다.
  • 시간 복잡도는 O(1)입니다.
  • 두 값의 타입이 같아야 합니다.
  • 기본 타입, STL 컨테이너, 사용자 정의 타입 등에 사용할 수 있습니다.
  • 사용자 정의 타입에 대해서는 이동 생성자와 이동 대입 연산자가 정의되어 있어야 합니다.
  • std::move를 사용하여 이동 시맨틱을 활용할 수 있습니다.
  • swap_ranges는 두 범위의 요소들을 교환하는 버전입니다.
  • iter_swap은 두 반복자가 가리키는 요소들을 교환하는 버전입니다.
  • 컨테이너의 swap 멤버 함수는 더 효율적일 수 있습니다.
함수 설명
swap(a, b) 두 값 a와 b의 위치를 서로 바꿈