将一串数字的前a位与后b位互换位置

本文介绍了一种通过C++实现的数字串位移算法,该算法可以将一串数字的前a位与后b位进行互换。文章详细展示了算法的具体实现过程,包括如何使用模板函数来提高代码的通用性和效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

将一串数字的前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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值