编程语言
首页 > 编程语言> > C++-对double、int 类型数组去重

C++-对double、int 类型数组去重

作者:互联网

#include <iostream>
#include <vector>
#include <set>
#include<iomanip>
#include <algorithm>

using namespace std;

void IntArrayRemoveRepeat(int array[], int length)
{
    set<int> intArray;
    
    for (int i = 0; i < length; ++i)
    {
        intArray.insert(array[i]);
    }

    set<int>::iterator it;

    for (it = intArray.begin(); it != intArray.end(); ++it)
    {
        cout << *it << endl;
    }
}

void DoubleArrayRemoveRepeat(double array[], int length)
{
    set<double> doubleArray;
 
    for (int i = 0; i < length; ++i)
    {
        for (int j = i + 1; j < length; ++j)
        {
            //对于double类型的数组,个人认为利用差值法比较好一点,仅供参考。
            if (fabs(array[i] - array[j]) <= 0.00001)
            {
                array[j] = array[i];
            }
        }
        doubleArray.insert(array[i]);
    }

    for (set<double>::iterator it = doubleArray.begin(); it != doubleArray.end(); ++it)
    {
        cout << *it << endl;
    }  
}

int main()
{
    cout << "*************int 类型*************" << endl;
    int array1[15] = { 5, 6, 7, 7, 8, 8, 8, 9, 9, 9, 10, 11, 11, 13, 15 };
    int length1 = sizeof(array1) / sizeof(array1[0]);
    IntArrayRemoveRepeat(array1, length1);

    cout << "*************double 类型*************" << endl;
    double array2[8] = { 5.02, 5.02, 5.08, 4.5, 3.5, 3.500001, 3.530, 3.550001};
    int length2 = sizeof(array2) / sizeof(array2[0]);
    DoubleArrayRemoveRepeat(array2, length2);
    //double array2 = 3.500001;
    
    return 0;
}

标签:int,double,C++,++,length,intArray,array,include
来源: https://www.cnblogs.com/xbnxopen/p/15102323.html