题目
将一串数字的前a位与后b位互换位置。
例如:
数字串:1 2 3 4 5
将前1位 与 后2位互换
结果;4 5 2 3 1
#include <iostream>
#include <cstring>
using namespace std;
//返回数组的长度
template <class T>
int getArrayLen(T& k)
{
return (sizeof(k) / sizeof(k[0]));
}
//将两个数内容互换
template<class array_type>
void exchange(array_type& a,array_type& b){
array_type temp;
temp = a;
a = b;
b = temp;
}
//将数组Array的[a,b]区间内的数颠倒
template<class array_type>
void Swap(array_type& Array,int a,int b){
int Head=a-1,End=b-1;
while(Head<End){
exchange(Array[Head++],Array[End--]);
}
}
//打印数组内容
template<class array_type>
void printArray(const array_type& a){
for(int i=0;i<getArrayLen(a);i++){
cout<<a[i]<<" ";
}
cout<<endl;
}
int main()
{
int num[]={1,2,3,4,5,6};
int a,b,len=getArrayLen(num);
cout<<"please input a & b:"<<endl;
cin>>a>>b;
Swap(num,1,a); //12345
Swap(num,len-b+1,len); //12354
Swap(num,1,len); //45321
Swap(num,b+1,len-a); //45231
printArray(num);
return 0;
}