💡 퀵 접속: cpp.kr/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(a, b) | 반복자 a와 b가 가리키는 요소들의 값을 서로 교환 |