简体   繁体   English

如何制作 function 从传递的数组中删除重复项

[英]How to make a function that remove duplicates from an passed array

It's my first year learning the C++ language.这是我学习 C++ 语言的第一年。 I want to make a function that removes duplicates from a passed array.我想做一个 function 从传递的数组中删除重复项。 I tried to doing it with many different kinds of logic, but sadly I have failed on all of them.我试图用许多不同的逻辑来做这件事,但遗憾的是我都失败了。 I hope someone can help me.我希望有一个人可以帮助我。

Here is my code:这是我的代码:

using namespace std;
#include <iostream>

void RemoveDuplicates(int * array,int n,int *&arrayb)
{
    int x=0;
    int y=0;
    for (int i=0;i<n;i++)
    {
        y++;
        if (array[x]!=array[y])
        {
            arrayb[x]=array[x];
            x++;
            y++;
        }
        else 
        {
            arrayb[x]=array[x];
            x++;
            y++;
            break;
        }
    }
}

int main()
{
    int n;
    cin >> n;
    int * array = new int [n];
    int * arrayb = new int [n];
    int i=0;
    for (i=0;i<n;i++)
    {
        cin>>array[i];
    }
    RemoveDuplicates(array,n,arrayb);

    for (int i=0;i<n;i++)
    {
        cout << arrayb[i] <<"  ";
    }
    system("pause");
}

My two cents on this, I had this piece of code in my repo我的两分钱,我的回购中有这段代码

void remove_duplicates(int arr[], int &a_size) {
    for (int i = 0; i < a_size; i++) {
        for (int j = i + 1; j < a_size;j++) {
            if (arr[i] == arr[j]) {
                for (int k = j; k < a_size; k++) {
                    arr[k] = arr[k + 1];
                }
                a_size--;
                j--;
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM