我如何只使用循环来实现这样的功能?
我快崩溃了,我似乎无法理清思路。
这就是我想出的,但还差得远呢。
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/