C++虚析构和(2)找出数组中唯一的重复元素

  1. 虚析构主要为了实现类多态之间层层虚构,减少内存泄漏。
  2. 如果不用虚析构,代码如下:
  3. #include
    using namespace std;
    class B
    {
    public:
    B()
    {
    cout << “B()” << endl;
    }
    ~B()
    {
    cout << “~B()” << endl;
    }
    };
    class A :public B
    {
    public:
    A()
    {
    cout << “A()” << endl;
    }
    ~A()
    {
    cout << “~A()” << endl;
    }
    };
    int main()
    {
    B a = new A();
    delete a;
    system(“pause”);
    return 0;
    }
    执行结果如下:
    在这里插入图片描述
    A的析构函数的没有走到,从而导致了A的自己的变量内存泄漏。
    加上虚析构
    #include
    using namespace std;
    class B
    {
    public:
    B()
    {
    cout << “B()” << endl;
    }
    virtual ~B()
    {
    cout << “~B()” << endl;
    }
    };
    class A :public B
    {
    public:
    A()
    {
    cout << “A()” << endl;
    }
    ~A()
    {
    cout << “~A()” << endl;
    }
    };
    int main()
    {
    B a = new A();
    delete a;
    system(“pause”);
    return 0;
    }
    执行结果如下:
    在这里插入图片描述
    这样就会执行A的析构函数。
    (2)找出数组中唯一重复的元素。
    intarr[101],存满了1-100,其中有一个数字是重复的的。请找出来。
    (1)我们可以定义一个map。找到重复的直接返回,但是map占用空间。
    (2)我们可以求出数组的和,减去1-100的和,就是重复的数字。
    (3)我们可以用可以用数组的下标和元素之间的关系。取一个位置的数组值,index=intarr[length-1]-1(其他位置元素容易出问题),我们把intarr[index]的值
    (-1)。然后index=intarr[index]
    (-1)-1;直到找到intarr[index]为负值,返回index+1即可。代码如下:
    #include
    using namespace std;
    int getUnique(int intarr[], int length)
    {
    int index = intarr[length - 1] - 1;
    while (true)
    {
    if (intarr[index] < 0)
    {
    break;
    }
    intarr[index] *= -1;
    index = intarr[index] * (-1) - 1;
    }
    return index + 1;
    }
    int main()
    {
    int intarr[10] = { 1,2,5,9,6,3,7,4,8,6 };
    cout << getUnique(intarr, 10) << endl;
    system(“pause”);
    return 0;
    }
    第三种方法也有很多种的推广,需要多多使用啊。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值