'C++' std::rotate

토스트·2024년 12월 27일

'C++' std::algorithm

목록 보기
7/11

rotate

template<class ForwardIt>
ForwardIt rotate(ForwardIt first, ForwardIt middle, ForwardIt last); //constexpr since C++ 20

C++17 ~

template<class ExecutionPolicy, class ForwardIt>
ForwardIt rotate(ExecutionPolicy&& policy, Forwardit first, ForwardIt middle, Forwardit last);

: 주어진 범위의 요소들을 회전시킨 후 기존의 first 위치가 가리키는 요소의 위치를 반환합니다.

  • first : 회전 작업을 시작할 첫 번째 요소를 가리키는 순방향 반복자
  • middle : 새로운 첫 번째 요소가 될 위치를 가리키는 순방향 반복자
  • last : 회전 작업을 수행할 마지막 번째 요소의 다음 위치를 가리키는 순방향 반복자
  • policy : 실행 정책

실행 정책은 std::execution 헤더에 포함되어있습니다.

  • execution::seq : 순차 실행 (기본 값)
  • execution::par : 병렬 실행 (멀티코어 시스템에서 작업이 병렬로 수행됩니다.)
  • execution::par_unseq : 병렬 및 비순차 실행

<example>

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

using namespace std;

int main() {
	vector<int> vec = {1, 2, 3, 4, 5};
    
    rotate(vec.begin(), vec.begin() + 2, vec.end()); // 왼쪽으로 회전합니다.
    // {1, 2, 3, 4, 5} -> {2, 3, 4, 5, 1} -> {3, 4, 5, 1, 2}
    
    for (const int & i : vec) {
    	cout << i << " ";
    }
    
    cout << endl;
    
    rotate(vec.rbegin(), vec.rbegin() + 2, vec.rend()); // 오른쪽으로 회전합니다.
    // {3, 4, 5, 1, 2} -> {2, 3, 4, 5, 1} -> {1, 2, 3, 4, 5}
    
    for (const int & i : vec) {
    	cout << i << " ";
    }

	return 0;
}

결과값

0개의 댓글