交换两个元素值的重载函数(C++)

题目详情
编写交换两个元素值的重载函数,两个元素会是两个整数、两个实数、两个整型数组、两个char型字符串。编写主函数,定义有关变量、数组,输入数据,调用函数,输出交换结果。数组元素不超过100。主函数如下(其中print(是前面编写的显示数组元素的函数):
在这里插入图片描述

输入:5行;分别是两整数,两实数,数组1,数组2,两个字符串。见样例输入。其中数组行的第1个数是元素个数。

输出:5行,交换的结果,见样例输出。

【注意】不能使用系统的字符串处理库函数,不使用string。可以自定义需要的函数。
【提示】整数、实数的交换使用参数的引用传递;数组的交换,元素个数的交换使用引用传递。

样例1输入:
2 3
1.2 1.81
3 1 2 3
8 81 82 83 84 85 86 87 88
input output

样例1输出:
3 2
1.81 1.2
81 82 83 84 85 86 87 88
1 2 3
output input

  • 下面代码
#include <iostream>
using namespace std;

void swap(int &a,int &b)
{
 int temp;
 temp=a;
 a=b;
 b=temp;
}

void swap(double &a,double &b)
{
 double temp;
 temp=a;
 a=b;
 b=temp;
}

void swap(int *a,int &n,int *b,int &m)
{
 int N = n>m? n:m;
 for(int i=0;i<N;i++)
 {
  swap(a[i],b[i]);
 }
 int temp;
 temp=n;
 n=m;
 m=temp;
}

void swap(char *p1, char *p2)
{
 int len1=0,len2=0,i=0;
 while(p1[i++]!='\0') len1++;
 i=0;
 while(p2[i++]!='\0') len2++;
 
 for( i=0;p1[i]!='\0'||p2[i]!='\0';i++)
 {
  swap(p1[i],p2[i]);
 }
 p1[len2]='\0';
 p2[len1]='\0';
}

void print(int *p, int n)
{
 if(n!=0) cout<<p[0];
 for(int i=1;i<n;i++)
 {
  cout<<' '<<p[i];
 }
 cout<<endl;
}
void print(double *p, int n)
{
 if(n!=0) cout<<p[0];
 for(int i=1;i<n;i++)
 {
  cout<<' '<<p[i];
 }
 cout<<endl;
}

int main()
{
 int a,b;
 double da,db;
 int aa[100],ab[100];
 char s1[100],s2[100];
 int n,m;
 int i;
 cin>>a>>b;
 cin>>da>>db;
 cin>>n;
 for(i=0;i<n;i++)
 {
  cin>>aa[i];
 }
 cin>>m;
 for(i=0;i<m;i++)
 {
  cin>>ab[i];
 }
 cin>>s1>>s2;
 swap(a,b);
 swap(da,db);
 swap(aa,n,ab,m);
 swap(s1,s2);
 cout<<a<<' '<<b<<endl;
 cout<<da<<' '<<db<<endl;
 print(aa,n);
 print(ab,m);
 cout<<s1<<' '<<s2<<endl;
 
 return 0;
}
发布了23 篇原创文章 · 获赞 1 · 访问量 1494

猜你喜欢

转载自blog.csdn.net/qq_45732909/article/details/104965900