Array(类与对象)

Array(类与对象)

题目描述

以上是数组类Array的数据成员,请为它补充以下方法:1、缺省构造函数,建立一个默认大小为10的数组;2、有参数构造函数,参数为所要建立的数组的大小;3、拷贝构造函数;4、析构函数;5、input方法,为数组元素赋值;6、output方法,输出数组元素;7、sort方法,给数组排序;8、insert(int value),插入方法,将参数value的值插入到数组中;9、mdelete(int index),删除方法,删除序号为index的元素。

输入

测试数据的组数 t

第一个数组的大小

数组元素的值

需要插入的值

需要删除的序号

........

输出

排序后的数组元素列表

插入后的数组元素列表

删除后的数组元素列表

样例输入

2
6
5 3 0 6 8 -1
-1
1
4
5 0 3 2
4
4

样例输出

Constructor.
after sort:-1 0 3 5 6 8
after insert:-1 -1 0 3 5 6 8
after delete:-1 0 3 5 6 8
Distructor.
Constructor.
after sort:0 2 3 5
after insert:0 2 3 4 5
after delete:0 2 3 4
Distructor.

【my code】

#include <iostream>
using namespace std;
 
class Array{
private:
    int *a;
    int size;
     
public:
    Array(){
        a = new int[10];
        size = 10;
        cout << "Constructor." << endl;
    }
    Array(int _size) {
        a = new int[_size];
        size = _size;
        cout << "Constructor." << endl;
    }
    Array(Array& array){
        size = array.size;
        a = new int[size];
        for(int i = 0; i < size; i++) {
            a[i] = array.a[i];
        }
        cout << "Constructor." << endl;
    }
     
    ~Array() {
        delete[] a;
        cout << "Distructor." << endl;
    }
     
     
    void input() {
        for(int i = 0; i < size; i++) {
            cin >> a[i];
        }
    }
     
    void output() {
        for(int i = 0; i < size-1; i++) {
            cout << a[i] << ' ';
        }
        cout << a[size-1] << endl;
    }
     
    void sort() {
        for(int i = 1; i < size; i++){  
            int key = a[i];  
            int j = i - 1;  
            while(j>=0&&a[j]>key){  
                a[j+1] = a[j];  
                j--; 
            }  
            a[j+1] = key;  
        }           
    }
     
    void insert(int value) {
        int* tmp=new int[size+1];
        for(int i=0;i<size;i++){
            tmp[i]=a[i];
        }
        tmp[size]=value;
         
        delete[] a;
        a=tmp;
        size++;
         
        sort();
    }
     
    void del(int index) {
        if(index<0||index>size-1)
            return;
             
        a[index]=a[size-1];
        size--;
         
        sort();
    }
};
 
int main() {
    int t;
    cin >> t;
    while(t--) {
        int size;
        cin >> size;
        Array array(size);
         
        array.input();
        array.sort();
        cout<<"after sort:";
        array.output();
         
        int value;
        cin >> value;
        array.insert(value);
        cout<<"after insert:";
        array.output();
         
        int index;
        cin >> index;
        array.del(index);
        cout<<"after delete:";
        array.output();
    }
     
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Xindolia_Ring/article/details/80280843