编写程序从数组中删除重复项

To write a program to remove duplicates from an array

本文关键字:删除 数组 程序      更新时间:2023-10-16

我正在研究从数组中删除重复项的程序,我在这里使用三个函数:一个用于输入大小和数字,第二个函数用于删除重复项并返回没有重复项的数字,第三个函数只是一个报告显示大小和新数字,但我有问题,我不知道在报告或菲利普错误中我认为在哪一步:

函数‘int main()’:从‘int*’‘int’的转换无效,初始化‘void report(int, int)’的参数1

#include <iostream>
using namespace std;
const int size = 100;
void phillip(int[], int & );
/* Preconditions: Array of base type in declared and int varuable declared
   postconditions: the array is filled with values supllied by the user at
   the keybord. the user is assked how many values they want - this value is
   given to the second argument.
*/
int remdubs(int[], int noel);
/* Preconditions: An array of basetype int that  has noel values.
   postconditions: The number of unique elemts in the array is returned. The function removes all dubplicates inside the array.
*/
void report(int s, int d);
int main()
{
    int ruby[size];
    int numele, numuniq;
    phillip(ruby, numele);
    numuniq = remdubs(ruby, numele);
    report(ruby, numuniq);
    return 0;
}
void phillip(int[], int& )
{
    int s;
    cout << "nHow many values you want? ";
    cin >> s;
    cout << "nPlease input 10 integers, hitting return after each one n";
    for (int i = 0; i < s; i++)
    {
        int num;
        cin >> num;
    }
}
int rembups(int sapphire[], int noel)
{
    for (int i = 0; i < noel; i++)
    {
        for (int j = i + 1; j < noel; j++)
        {
            if (sapphire[i] == sapphire[j])
            {
                for (int k = j; k < noel; k++)
                    sapphire[k] = sapphire[k + 1];
                noel--;
                j--;
            }
        }
    }
    return noel;
}
void report(int s, int d)
{
    cout << "nYou entered " << s << "distinct numbers: " << d;
}

没有比你的错误更好的解释了:

void report (int s, int d);

这个函数要求两个整数值,你正在传递一个数组给它,它的功能衰减了,将表现得像一个整数指针

int ruby[size];
report (ruby, numuniq);

我不确定你的程序的行为,但你应该做一些像

report(ruby[0], numuniq);

即:访问数组中的元素并将其提供给函数

错误是在函数报告中,它要求两个整数,而您正在传递一个数组和一个整数我认为在函数报告中不需要两个参数一个就可以了

void report(int d) { cout << "nYou entered <<d<<" distinct numbers"; }

可以解决你的错误,但我不认为你会得到你想要的输出

代码的几个问题:

  • Report函数应该期望一个整数数组,而不是单个整数
  • 尝试使用人类可读的变量名或函数名
  • remdubs在函数定义
  • 中重命名为rempubs
  • phillip函数定义没有正确定义参数
  • 你有const int size,但不要使用它
  • remdups有一个bug。我将把它留在这里,因为我正试图解决其他问题。
  • 有比remdups更好的方法来查找副本。请考虑其他解决方案。

我已经修复了你的代码,并提供了它在ideone