旋转元素次序:rotate
源码:
template<class _RanIt,
class _Diff,
class _Ty> inline
void _Rotate(_RanIt _First, _RanIt _Mid, _RanIt _Last, _Diff *, _Ty *)
{ // rotate [_First, _Last), random-access iterators
_Diff _Shift = _Mid - _First;
_Diff _Count = _Last - _First;
for (_Diff _Factor = _Shift; _Factor != 0; )//求最大公因子
{ // find subcycle count as GCD of shift count and length
_Diff _Tmp = _Count % _Factor;
_Count = _Factor;
_Factor = _Tmp;
}
if (_Count < _Last - _First)
for (; 0 < _Count; --_Count)
{ // rotate each subcycle
_RanIt _Hole = _First + _Count;
_RanIt _Next = _Hole;
_RanIt _Next1 = _Next + _Shift == _Last ? _First : _Next + _Shift;
for (; ; )
{ // percolate elements back around subcycle
iter_swap(_Next, _Next1);
_Next = _Next1;
_Next1 = _Shift < _Last - _Next1 ? _Next1 + _Shift
: _First + (_Shift - (_Last - _Next1));
if (_Next1 == _Hole)
break;
}
}
}
int main()
{
vector<int> vecInt;
for( int i = 0;i < 10;++ i )
{
vecInt.push_back( i * 10 );
}
rotate( vecInt.begin(),vecInt.begin() + 7,vecInt.end() );
copy( vecInt.begin(),vecInt.end(),ostream_iterator<int>( cout," " ) );
system( "pause" );
return 0;
}
这段代码确实难懂,看了几遍没有看懂.
想去借助源码剖析,结果听失望的,侯捷对于forward和bidirectional iterator两个版本有细致的讲解,唯独random access iterator没有.
前面两个算法易懂,关键是后一个算法.__rotate_cycle在干嘛呢?这样做有的原理是啥呢?还是不清楚.感觉侯捷可能自己也没法讲解,"故意"跳过.
关于这个函数的讲解可能就暂时过了.去Google一下,发现在博客园里面有一篇文章对后面的那个函数解释的比较详细.但是它说到数论,这个没有学过.很可惜.
暂时先过吧.