💡 퀵 접속: cpp.kr/rotate

rotate

C++ 표준 라이브러리의 알고리즘으로, 주어진 범위의 요소들을 회전시킵니다. rotate는 원본 범위를 직접 수정하며, 지정된 위치를 기준으로 왼쪽으로 회전시킵니다. 즉, 지정된 위치의 요소가 범위의 첫 번째 위치로 이동하고, 그 이전의 요소들은 범위의 끝으로 이동합니다.

기본 사용법

#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;
    
    // 3번째 요소(3)를 기준으로 회전
    std::rotate(numbers.begin(), numbers.begin() + 2, numbers.end());
    
    std::cout << "회전 후 벡터: ";
    for (int n : numbers) std::cout << n << " ";
    std::cout << std::endl;
    
    return 0;
}

실행 결과:

원본 벡터: 1 2 3 4 5
회전 후 벡터: 3 4 5 1 2

문자열에서 사용

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

int main() {
    std::string text = "Hello, World!";
    
    std::cout << "원본 문자열: " << text << std::endl;
    
    // 6번째 문자(쉼표)를 기준으로 회전
    std::rotate(text.begin(), text.begin() + 5, text.end());
    
    std::cout << "회전 후 문자열: " << text << std::endl;
    
    return 0;
}

실행 결과:

원본 문자열: Hello, World!
회전 후 문자열: , World!Hello

사용자 정의 타입에서 사용

#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();
    }
    
    // Charlie를 기준으로 회전
    std::rotate(people.begin(), people.begin() + 2, 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세)

회전 후 목록:
Charlie (25세)
David (35세)
Eve (22세)
Alice (20세)
Bob (30세)

참고사항

  • rotate는 algorithm 헤더에 정의되어 있습니다.
  • 원본 범위를 직접 수정합니다.
  • 시간 복잡도는 O(n)입니다.
  • 요소들의 순서가 회전되지만, 요소들의 값은 변경되지 않습니다.
  • 예외 안전성을 보장합니다.
  • rotate_copy는 원본을 수정하지 않고 결과를 다른 범위에 복사하는 버전입니다.
함수 설명
rotate(first, middle, last) 범위 [first, last)에서 middle 위치의 요소가 첫 번째 위치로 오도록 회전