當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C++ rotate用法及代碼示例


該函數在頭文件<algorithm>中定義。它以[first,last]範圍內的元素順序旋轉,以這種方式使得由Middle指向的元素成為新的第一個元素。
函數模板:

void rotate(ForwardIterator first, ForwardIterator middle, ForwardIterator last)
first, last: Forward Iterators to the initial and final positions of the sequence to be rotated
middle: Forward Iterator pointing to the element within the range [first, last] that is moved to the first position in the range.

Types of Rotations



  1. 左旋:要向左旋轉,我們需要添加矢量索引。例如,您必須將向量向左旋轉3次。向量的第三個索引成為第一個元素。 vec.begin() + 3將向量向左旋轉3次。
  2. 右旋:要向右旋轉,我們需要減去向量索引。例如,您必須將向量右旋轉3次。向量的最後3個索引成為第一個元素。 vec.begin() + vec.size()-3將向量向右旋轉3次。
  3. 例子:

    Input:1 2 3 4 5 6 7 8 9
    Output:
    Old vector:1 2 3 4 5 6 7 8 9
    New vector:4 5 6 7 8 9 1 2 3 // Rotated at 3th position, starting index as 0.

    Input:8 2 4 6 11 0 15 8
    Output:
    Old vector:8 2 4 6 11 0 15 8
    New vector:0 15 8 8 2 4 6 11 //Rotated at 5th position, starting index as 0.

    // CPP program to rotate vector 
    // using std::rotate algorithm 
      
    #include<bits/stdc++.h> 
      
    int main () { 
        std::vector<int> vec1{1,2,3,4,5,6,7,8,9}; 
      
        // Print old vector 
        std::cout << "Old vector:"; 
        for(int i=0; i < vec1.size(); i++) 
            std::cout << " " << vec1[i]; 
        std::cout << "\n"; 
        // Rotate vector left 3 times. 
        int rotL=3; 
      
        // std::rotate function 
        std::rotate(vec1.begin(), vec1.begin()+rotL, vec1.end()); 
      
        // Print new vector 
        std::cout << "New vector after left rotation:"; 
        for (int i=0; i < vec1.size(); i++) 
            std::cout<<" "<<vec1[i]; 
        std::cout << "\n\n"; 
      
        std::vector <int> vec2{1,2,3,4,5,6,7,8,9}; 
      
        // Print old vector 
        std::cout << "Old vector:"; 
        for (int i=0; i < vec2.size(); i++) 
            std::cout << " " << vec2[i]; 
        std::cout << "\n"; 
      
        // Rotate vector right 4 times. 
        int rotR = 4; 
      
        // std::rotate function 
        std::rotate(vec2.begin(), vec2.begin()+vec2.size()-rotR, vec2.end()); 
      
        // Print new vector 
        std::cout << "New vector after right rotation:"; 
        for (int i=0; i < vec2.size(); i++) 
            std::cout << " " << vec2[i]; 
        std::cout << "\n"; 
      
    return 0; 
    }

    輸出:

    Old vector:1 2 3 4 5 6 7 8 9
    New vector after left rotation:4 5 6 7 8 9 1 2 3
    
    Old vector:1 2 3 4 5 6 7 8 9
    New vector after right rotation:6 7 8 9 1 2 3 4 5
    

    時間複雜度:Theta(n),其中n是給定範圍內的元素數。




相關用法


注:本文由純淨天空篩選整理自 rotate in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。