微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐