大佬教程收集整理的这篇文章主要介绍了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
以上是大佬教程为你收集整理的C按以下顺序切换数组顺序的算法:[Last,First,Last – 1,First 1 …]全部内容,希望文章能够帮你解决C按以下顺序切换数组顺序的算法:[Last,First,Last – 1,First 1 …]所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。