💡 퀵 접속: cpp.kr/reverse
C++ 표준 라이브러리의 알고리즘으로, 주어진 범위의 요소들의 순서를 반대로 뒤집습니다. reverse는 원본 범위를 직접 수정하며, 범위의 첫 번째 요소와 마지막 요소를 교환하고, 그 다음 요소들도 순차적으로 교환하는 방식으로 동작합니다.
#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::reverse(numbers.begin(), numbers.end());
std::cout << "뒤집은 벡터: ";
for (int n : numbers) std::cout << n << " ";
std::cout << std::endl;
return 0;
}
실행 결과:
원본 벡터: 1 2 3 4 5 뒤집은 벡터: 5 4 3 2 1
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string text = "Hello, World!";
std::cout << "원본 문자열: " << text << std::endl;
// 문자열의 문자들을 반대로 뒤집기
std::reverse(text.begin(), text.end());
std::cout << "뒤집은 문자열: " << text << std::endl;
return 0;
}
실행 결과:
원본 문자열: Hello, World! 뒤집은 문자열: !dlroW ,olleH
#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;
}
};
int main() {
std::vector<Person> people = {
Person("Alice", 20),
Person("Bob", 30),
Person("Charlie", 25),
Person("David", 35),
Person("Eve", 22)
};
std::cout << "원본 목록:" << std::endl;
for (const auto& person : people) {
person.print();
}
// Person 객체들의 순서를 반대로 뒤집기
std::reverse(people.begin(), people.end());
std::cout << "\n뒤집은 목록:" << std::endl;
for (const auto& person : people) {
person.print();
}
return 0;
}
실행 결과:
원본 목록: Alice (20세) Bob (30세) Charlie (25세) David (35세) Eve (22세) 뒤집은 목록: Eve (22세) David (35세) Charlie (25세) Bob (30세) Alice (20세)
| 함수 | 설명 |
|---|---|
| reverse(first, last) | 범위 [first, last)의 요소들의 순서를 반대로 뒤집음 |