该函数在头文件
函数模板:
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.
旋转类型
- 左旋转:要向左旋转,我们需要添加矢量索引。例如,您必须将向量向左旋转3次。向量的第三个索引成为第一个元素。 vec.begin()+ 3将向量向左旋转3次。
- 向右旋转:要向右旋转,我们需要减去向量索引。例如,您必须将向量右旋转3次。向量的最后3个索引成为第一个元素。 vec.begin()+ vec.size()-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
int main () { std::vector 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<<" "< 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是给定范围内的元素数。
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。