STLalgorithm算法rotate,rotate_copy(51)


STLalgorithm算法rotate,rotate_copy(51)

rotate原型:

std::rotate

template <class ForwardIterator>
  ForwardIterator rotate (ForwardIterator first, ForwardIterator middle,
                          ForwardIterator last);

该函数是循环移位函数。

效果是交换[middle,last)和[first,middle)部分的位置。

具体实现请自行搜索。

类似实现为:

template <class ForwardIterator>
  void rotate (ForwardIterator first, ForwardIterator middle,
               ForwardIterator last)
{
  ForwardIterator next = middle;
  while (first!=next)
  {
    swap (*first++,*next++);
    if (next==last) next=middle;
    else if (first==middle) middle=next;
  }
}

一个简单的例子:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
void mrotate()
{
    vector<int> vi{1,2,3,4,5,6};
    vector<int> vresult{10,20,30,40,50};
    cout<<"vi=";
    for(int i:vi)
        cout<<i<<" ";
    cout<<endl;
    cout<<"vresult=";
    for(int i:vresult)
        cout<<i<<" ";
    cout<<endl;
    rotate(vi.begin(),vi.begin()+3,vi.end());
    rotate(vresult.begin(),vresult.end()-1,vresult.end());
    cout<<"after     rotate(vi.begin(),vi.begin()+3,vi.end())"<<endl;
    cout<<"vi=";
    for(int i:vi)
        cout<<i<<" ";
    cout<<endl;
    cout<<"after rotate(vresult.begin(),vresult.end()-1,vresult.end());"<<endl;

    cout<<"vresult=";
    for(int i:vresult)
        cout<<i<<" ";
    cout<<endl;



}

运行截图:


rotate_copy原型:

std::rotate_copy

template <class ForwardIterator, class OutputIterator>
  OutputIterator rotate_copy (ForwardIterator first, ForwardIterator middle,
                              ForwardIterator last, OutputIterator result);

该函数是将rotate后的序列存放到result开始的位置。

实现类似于:

template <class ForwardIterator, class OutputIterator>
  OutputIterator rotate_copy (ForwardIterator first, ForwardIterator middle,
                              ForwardIterator last, OutputIterator result)
{
  result=std::copy (middle,last,result);
  return std::copy (first,middle,result);
}

一个简单的例子:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
void mrotatecopy()
{
    vector<int> vi{1,2,3,4,5,6};
    vector<int> vresult(6);
    cout<<"vi=";
    for(int i:vi)
        cout<<i<<" ";
    cout<<endl;
    cout<<"vresult=";
    for(int i:vresult)
        cout<<i<<" ";
    cout<<endl;
    rotate_copy(vi.begin(),vi.begin()+3,vi.end(),vresult.begin());
    cout<<"after rotate_copy(vi.begin(),vi.begin()+3,vi.end(),vresult.begin())"<<endl;
    cout<<"vi=";
    for(int i:vi)
        cout<<i<<" ";
    cout<<endl;

    cout<<"vresult=";
    for(int i:vresult)
        cout<<i<<" ";
    cout<<endl;



}


运行截图:

——————————————————————————————————————————————————————————————————

//写的错误或者不好的地方请多多指导,可以在下面留言或者点击左上方邮件地址给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。

转载请注明出处:http://blog.csdn.net/qq844352155

author:天下无双

Email:coderguang@gmail.com

2014-9-26

于GDUT

——————————————————————————————————————————————————



发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注