当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。