• C++面向对象编程题 第22题


    22. 试定义一个类 NUM,实现将一维数组中各整数元素去年去掉相同数字后再对数组从小到大排序。将一个整数去掉相同数字是指:如果一个整数中有相同的数字,则保留从左数起,第一次看到的那个数
    字,而将其它的数字去掉。例如:数字 12324151 中有三个 1,两个 2,则去掉相同的数字后变为 12345。

    具体要求如下:

    1. 私有数据成员
    • int *a;存放需要处理的数据。
    • int n;长度
    1. 公有成员函数
    • NUM(int t[],int len);构造函数,用t初始化a, len为t的元素个数。
    • void sort(int t[]);将数组t的元素从小到大排序。
    • int convert(int n);去除n中相同的数字并返回新得到的数。
    • int fun();将数组a的各元素去除相同的数字后从小到大排列。要求调用函数 convert()和sort()
    • void print();输出数组a的所有元素。
    1. 在主函数中对该类进行测试。
      用int a[5]={1213,65666,212313,12434,34435};这一数组初始化NUM n
      输出:
      1213 65666 212313 12434 34435
      65 123 213 345 1243
    #include
    using namespace std;
    class NUM{
        int *a,n;
    public:
        NUM(int t[],int len){
            n=len;
            a=new int[n];
            for(int i=0;i<n;i++){
                a[i]=t[i];
            }
        }
        void sort(int t[]){
            for(int i=0;i<n-1;i++){
                for(int j=0;j<n-1-i;j++){
                    if(a[j]>a[j+1]){
                        int a=t[j];
                        t[j]=t[j+1];
                        t[j+1]=a;
                    }
                }
            }
        }
        int convert(int n){
            int t[100],count=0;
            while(n){
                t[count++]=n%10;
                n/=10;
            }
            int sum=0;
            for(int i=count-1;i>=0;i--){
                int j;
                for(j=count-1;j>i;j--){
                    if(t[i]==t[j])break;
                }
                if(i==j){
                	sum=sum*10+t[i];
                }
            }
            return sum;
        }
        void fun(){
            for(int i=0;i<5;i++){
                a[i]=convert(a[i]);
            }
            sort(a);
        }   
        void print(){
            for(int i=0;i<n;i++)cout<<a[i]<<' ';
            cout<<endl;
        }
    };
    int main(){
        int a[5]={1213,65666,212313,12434,34435};
        NUM num(a,5);
        num.print();
        num.fun();
        num.print();
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
  • 相关阅读:
    机器学习笔记07---朴素贝叶斯分类器
    测试驱动的嵌入式C语言开发(TDD)(第1-3章)
    微信小程序开发入门与实战(数据监听)
    将java装进u盘指南
    如何使用Plotly和Dash进行数据可视化
    Jmeter提取协议报文、请求头、请求体、响应体
    LeetCode——Weekly Contest 318
    Linux中通配符的使用
    订单及其状态机的设计实现
    投资失败+转岗降薪,2年逆袭月薪30K,我的船终于靠了岸
  • 原文地址:https://blog.csdn.net/xskukuku/article/details/127976892