c++ std::rotate()的用法(一看就懂)

  • 进行元素范围上的左旋转
    用法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;现在应该就一目了然了。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44378800/article/details/106504704
今日推荐