C按以下顺序切换数组顺序的算法:[Last,First,Last – 1,First 1 …]

如何仅使用循环实现此类功能

我正在打破我的脑袋,我似乎无法直接思考.

这就是我想出来的,但它甚至都没有.

for (int i = 0; i < elements; i++)
{
    for (int n = elements; n > 0; --n)
        a[i] = b[n];
}

解决方法

这个给你

#include <iostream>
#include <algorithm>
#include <iterator>

int main()
{
    int a[] = { 0,1,2,3,4,5,6,7,8,9 };

    for ( int x : a ) std::cout << x << ' ';
    std::cout << std::endl;

    for ( auto it = std::begin( a ); it != std::end( a ); it == std::end( a ) ? it : ++it )
    {
        it = std::rotate( it,std::prev( std::end( a ) ),std::end( a ) );
    }        

    for ( int x : a ) std::cout << x << ' ';
    std::cout << std::endl;
}

程序输出

0 1 2 3 4 5 6 7 8 9 
9 0 8 1 7 2 6 3 5 4

编译器应支持C 11算法std :: rotate.

附:我改变了循环的第三个表达式,它对于具有奇数个元素的序列是正确的.

另一种方法是使用标准算法std :: copy_backward
像下面这样的东西

#include <iostream>
#include <algorithm>
#include <iterator>

template <class BidirectionalIterator>
void alternate( BidirectionalIterator first,BidirectionalIterator last )
{
    if ( first != last && first != --last )
    {
        while ( first != last )
        {
            auto value = *last;
            std::copy_backward( first,last,std::next( last ) );
            *first++ = value;
            if ( first != last ) ++first;
        }
    }
}    

int main()
{
    int a[] = { 0,9 };

    for ( int x : a ) std::cout << x << ' ';
    std::cout << std::endl;

    alternate( std::begin( a ),std::end( a ) );

    for ( int x : a ) std::cout << x << ' ';
    std::cout << std::endl;
}

程序输出

0 1 2 3 4 5 6 7 8 9 
9 0 8 1 7 2 6 3 5 4

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...