加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 10:36:25 所属栏目:百科 来源:网络整理
导读:如何仅使用循环实现此类功能? 我正在打破我的脑袋,我似乎无法直接思考. 这就是我想出来的,但它甚至都没有. for (int i = 0; i elements; i++){ for (int n = elements; n 0; --n) a[i] = b[n];} 解决方法 这个给你 #include iostream#include algorithm#inc
如何仅使用循环实现此类功能?

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读