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

标签 c++ arrays algorithm c++11 iterator

我如何只使用循环来实现这样的功能?

我快崩溃了,我似乎无法理清思路。

这就是我想出的,但还差得远呢。

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, 1, 2, 3, 4, 5, 6, 7, 8, 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++ 算法按以下顺序切换数组的顺序 : [Last, First, Last - 1, First + 1...],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35477139/

相关文章:

c++ - 检查一个点是否已经在 vector/列表中——性能

c++ - 如何在 Qt 中检测 Windows 事件?

c++ - 定义私有(private)静态类成员

javascript - jquery 删除数组中的空元素

Python:迭代具有不同维数的列表,有通用的方法吗?

c++ - 无法使用 FindWindowEx 函数找到子窗口

Javascript Concat 多维数组

c# - 如何在 C# 中实现 MaxSubArray?

python - 生成所有 5 张牌扑克手

c# - 组合总和