C/C++教程

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;
}
这篇关于C++-对double、int 类型数组去重的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!