- 進行元素範圍上的左旋轉
用法:std::rotate( first_element, n_first( will be the first element after ratating ), last_element )
關於這個函數的具體的用法編寫了如下代碼,相信大家看完之後會有一個較好的認識:
構造了兩個函數,分別對於數組和字符串操作:
//hmtian @ 2020/6/2 21:06
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<iterator>
#include<cstdlib>
#include<cstdio>
#include<cassert>
/****************************function**********************************/
void rotate_order1(std::vector<int>& arr, int num)
{
assert(num >= 0 && num < arr.size());
std::rotate(arr.begin(),arr.begin() + num, arr.end());
}
void rotate_order2(std::string& str, int num)
{
assert(num >= 0 && num < str.size());
std::rotate(str.begin(),str.begin() + num, str.end());
}
/*********************************************************************/
int main()
{
std::vector<int> arr = {1,2,3,4,5};
std::string str = "abcde";
for(int i = 0; i < arr.size(); i++)
{
rotate_order1(arr,i);
std::cout<<"[i]="<< i <<" ";
for(const auto& e : arr){
std::cout<< e ;}
std::cout<<"\n";
//std::cout<<" put the number of "<< i+1 << " element to the first position\n";
}
for(int i = 0; i < str.size(); i++)
{
rotate_order2(str,i);
std::cout<<"[i]="<< i <<" ";
for(const auto& e : str){
std::cout<< e ;}
std::cout<<"\n";
//std::cout<<" put the number of "<< i+1 << " element to the first position\n";
}
return 0;
}
輸出結果:
i = 0 時,意味着將第一個元素(arr.begin() + i)放在首位,之後 rotate後的數組或者字符串作爲下一輪循環的輸入,但是需要注意arr.begin()始終爲1;現在應該就一目瞭然了。