Sat*_*ama 3 c++ arrays algorithm iterator c++11
如何仅使用循环实现此类功能?
我正在打破我的脑袋,我似乎无法直接思考.
这就是我想出来的,但它甚至都没有.
for (int i = 0; i < elements; i++)
{
for (int n = elements; n > 0; --n)
a[i] = b[n];
}
Run Code Online (Sandbox Code Playgroud)
这个给你
#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;
}
Run Code Online (Sandbox Code Playgroud)
程序输出是
0 1 2 3 4 5 6 7 8 9
9 0 8 1 7 2 6 3 5 4
Run Code Online (Sandbox Code Playgroud)
编译器应支持C++ 11算法std::rotate.
PS我改变了循环的第三个表达式,它对于具有奇数个元素的序列是正确的.
另一种方法是使用标准算法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;
}
Run Code Online (Sandbox Code Playgroud)
程序输出是
0 1 2 3 4 5 6 7 8 9
9 0 8 1 7 2 6 3 5 4
Run Code Online (Sandbox Code Playgroud)