💡 퀵 접속: cpp.kr/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(a, b) | 두 값 a와 b의 위치를 서로 바꿈 |