试定义一个数组类CArray,声明如下: class CArray{ int *arr; //数组 int n; //数组元素个数 public: CArray(); //构造函数 CArray(int a[],int n); //构造函数 CArray(CArray &t); //拷贝构造函数 ~CArray(); int Insert(int x); //在数组中插入整数x,保持数组从小到大排序 void Print(); //输出数组 }; 在如下主函数中对该类进行测试。 int main() { int a[] = { 3,6,9 },x; CArray a1(a, 3),a2(a1); for (int i = 0; i < 5; i++) { cin >> x; a2.Insert(x); } a2.Print(); return 0; } 输入输出示意如下: 1 2 3 4 5 1 2 3 3 4 5 6 9 请在答题窗口录入编写的完整程序。
时间: 2024-01-27 18:03:50 浏览: 23
```
#include<iostream>
using namespace std;
class CArray{
private:
int *arr;
int n;
public:
CArray(){
arr = NULL;
n = 0;
}
CArray(int a[], int n){
this->n = n;
arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = a[i];
}
CArray(CArray &t){
this->n = t.n;
arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = t.arr[i];
}
~CArray(){
if (arr != NULL)
delete[] arr;
}
int Insert(int x){
int i;
for (i = 0; i < n; i++)
if (arr[i]>x)
break;
int *newarr = new int[n + 1];
for (int j = 0; j < i; j++)
newarr[j] = arr[j];
newarr[i] = x;
for (int j = i + 1; j < n + 1; j++)
newarr[j] = arr[j - 1];
delete[] arr;
arr = newarr;
n++;
return i;
}
void Print(){
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
};
int main(){
int a[] = { 3,6,9 }, x;
CArray a1(a, 3), a2(a1);
for (int i = 0; i < 5; i++){
cin >> x;
a2.Insert(x);
}
a2.Print();
return 0;
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)