如何通过将数组的指针传递给函数来查找数组的模式?C++

How do I find the mode of an array by passing the pointer of that array to a function? C++

本文关键字:数组 查找 模式 C++ 函数 何通过 指针      更新时间:2023-10-16

所以我对指针完全陌生,我为此道歉,我应该传递一个指针数组并获取该数组的模式。 数组作为一组指针传递后,我无法操作数组来查找模式,我尝试的所有内容都会导致语法错误。

编辑:我将列表更改为指针数组,并收到运行时错误。

int main()
{
int size=0;
int *list[size];
cout<<"Please enter the size of your array: ";
cin>>size;
cout<<"nPlease enter the numbers in your list seperated by spaces: ";
for(int i=0;i<size;i++)
{
    cin>>*list[i];
}
cout<<endl;

int mode=getMode(list,size);
cout<<"n"<<mode<<endl;
return 0;
}
int getMode (int* list[], int arraySize)
{
    cout<<"The array you entered is listed belown "<<list[0];
    for(int i=0;i<arraySize;i++)
        {cout<<setw(3)<<list[i];}
    int *number=list[0];
    int count1=0;
    int count2=0;
    int mode=0;
    for(int j=1;j<arraySize;j++)
        {
            for(int i=1;i<arraySize;i++)
                {
                    if(list[i]==number)
                        {
                            count1++; //counts the number of instances that the number occurs
                        }
                }
            if(count1>count2)
                {
                    mode= *list[j];
                    count2=count1;
                }
            count1=0;
        }
    return mode;
}

当你将数组传递给函数时,它会自动衰减到指针,所以你不需要使用 &list .而在函数中,你不应该int *list[]声明它,它应该只是int list[]int *list

另外,在getMode()函数中,您需要计算list[j]的匹配项。你只是在计算number的重复次数,这是list[0].

#include <iostream>
#include <iomanip>
using namespace std;
int getMode (int list[], int arraySize)
{
    cout<<"The array you entered is listed belown "<<list[0];
    for(int i=0;i<arraySize;i++)
        {cout<<setw(3)<<list[i];}
    int count1=0;
    int count2=0;
    int mode=0;
    for(int j=0;j<arraySize;j++)
        {
            for(int i=0;i<arraySize;i++)
                {
                    if(list[i]==list[j])
                        {
                            count1++; //counts the number of instances that the number occurs
                        }
                }
            if(count1>count2)
                {
                    mode= list[j];
                    count2=count1;
                }
            count1=0;
        }
    return mode;
}
int main()
{
    int size;
    int *list;
    cout<<"Please enter the size of your array: ";
    cin>>size;
    list=new int[size];
    cout<<"nPlease enter the numbers in your list seperated by spaces: ";
    for(int i=0;i<size;i++)
        {
            cin>>list[i];
        }
    cout<<endl;
    int mode=getMode(list,size);
    cout<<"n"<<mode<<endl;
    return 0;
}

演示