用C++++++++编写一个有序数组类,类定义为SortedArray,要求对两个任意长度的数组分别进行排序,之后再将这两个有序数组合并,代码中需要使用运算符的重载和索引
时间: 2024-05-21 07:10:54 浏览: 145
#include <iostream>
using namespace std;
class SortedArray
{
private:
int *arr;
int size;
public:
SortedArray(int *a, int n)
{
arr = new int[n];
size = n;
for(int i=0; i<n; i++)
{
arr[i] = a[i];
}
sort();
}
void sort()
{
for(int i=0; i<size-1; i++)
{
for(int j=i+1; j<size; j++)
{
if(arr[i]>arr[j])
{
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
}
SortedArray operator+(SortedArray &a)
{
int *newarr = new int[size+a.size];
int i=0, j=0, k=0;
while(i<size && j<a.size)
{
if(arr[i]<a.arr[j])
{
newarr[k++] = arr[i++];
}
else
{
newarr[k++] = a.arr[j++];
}
}
while(i<size)
{
newarr[k++] = arr[i++];
}
while(j<a.size)
{
newarr[k++] = a.arr[j++];
}
return SortedArray(newarr, size+a.size);
}
int operator[](int i)
{
return arr[i];
}
};
int main()
{
int a[] = {1, 3, 5, 7, 9};
int b[] = {2, 4, 6, 8, 10};
SortedArray A(a, 5);
SortedArray B(b, 5);
SortedArray C = A+B;
for(int i=0; i<10; i++)
{
cout<<C[i]<<" ";
}
cout<<endl;
return 0;
}
阅读全文