💡 퀵 접속: cpp.kr/iter_swap

iter_swap

C++ 표준 라이브러리의 알고리즘으로, 두 반복자가 가리키는 요소들의 값을 서로 교환합니다. 이 함수는 두 반복자가 가리키는 요소들의 타입이 같고 이동 가능(moveable)해야 합니다. iter_swap은 반복자를 사용하는 알고리즘에서 유용하게 사용됩니다.

기본 사용법

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    
    std::cout << "교환 전: ";
    for (int n : numbers) std::cout << n << " ";
    std::cout << std::endl;
    
    // 첫 번째와 마지막 요소 교환
    std::iter_swap(numbers.begin(), numbers.end() - 1);
    
    std::cout << "교환 후: ";
    for (int n : numbers) std::cout << n << " ";
    std::cout << std::endl;
    
    return 0;
}

실행 결과:

교환 전: 1 2 3 4 5
교환 후: 5 2 3 4 1

문자열 벡터에서 사용

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

int main() {
    std::vector<std::string> names = {"Alice", "Bob", "Charlie", "David"};
    
    std::cout << "교환 전:" << std::endl;
    for (const auto& name : names) {
        std::cout << name << " ";
    }
    std::cout << std::endl;
    
    // 두 번째와 세 번째 요소 교환
    std::iter_swap(names.begin() + 1, names.begin() + 2);
    
    std::cout << "교환 후:" << std::endl;
    for (const auto& name : names) {
        std::cout << name << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

실행 결과:

교환 전:
Alice Bob Charlie David
교환 후:
Alice Charlie Bob David

사용자 정의 타입에서 사용

#include <iostream>
#include <vector>
#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;
    }
    
    // swap을 위한 friend 함수
    friend void swap(Person& a, Person& b) {
        using std::swap;  // ADL을 위해
        swap(a.name, b.name);
        swap(a.age, b.age);
    }
};

int main() {
    std::vector<Person> people = {
        Person("Alice", 20),
        Person("Bob", 25),
        Person("Charlie", 30)
    };
    
    std::cout << "교환 전:" << std::endl;
    for (const auto& person : people) {
        person.print();
    }
    
    // 첫 번째와 마지막 요소 교환
    std::iter_swap(people.begin(), people.end() - 1);
    
    std::cout << "\n교환 후:" << std::endl;
    for (const auto& person : people) {
        person.print();
    }
    
    return 0;
}

실행 결과:

교환 전:
Alice (20세)
Bob (25세)
Charlie (30세)

교환 후:
Charlie (30세)
Bob (25세)
Alice (20세)

참고사항

  • iter_swap은 algorithm 헤더에 정의되어 있습니다.
  • 두 반복자가 가리키는 요소들의 타입이 같아야 합니다.
  • 이동 가능한(moveable) 타입에 대해서만 사용할 수 있습니다.
  • 시간 복잡도는 O(1)입니다.
  • 사용자 정의 타입에 대해서는 swap 함수를 오버로드하여 효율적인 교환을 구현할 수 있습니다.
  • ADL(Argument Dependent Lookup)을 위해 using std::swap을 사용하는 것이 좋습니다.
  • 반복자를 사용하는 알고리즘에서 유용하게 사용됩니다.
  • 예외 안전성을 보장합니다.
함수 설명
iter_swap(a, b) 반복자 a와 b가 가리키는 요소들의 값을 서로 교환