如何通过将数组的指针传递给函数来查找数组的模式?C++
How do I find the mode of an array by passing the pointer of that array to a function? C++
所以我对指针完全陌生,我为此道歉,我应该传递一个指针数组并获取该数组的模式。 数组作为一组指针传递后,我无法操作数组来查找模式,我尝试的所有内容都会导致语法错误。
编辑:我将列表更改为指针数组,并收到运行时错误。
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;
}
演示
相关文章:
- 在数组中查找总计
- 在二维数组中查找最小值和最大值?
- 如何查找哪个类对象位于数组的特定索引上(多态性)
- 查找自动生成键并具有线性内存消耗的小型关联数组
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 如何使用数组查找标准偏差
- 从列表到数组C 查找模式或最常见的数字
- 12个元素的数组 - 查找计数实践
- 使用数组查找HCF,获取未知输出(C )
- C++constexpr数组查找:内存开销?其他问题
- C++字符数组查找/替换字符
- 动态数组查找能力
- 用.用数组查找.C++
- 使用数组查找最大值
- 字典查找与数组查找;数组分配与字典分配
- 使用数组查找最接近的数字C++,浮点
- 定义一个非常大的数组(查找表)的最佳方式是什么
- Std::数组查找最大值函数
- Python在简单数组查找上的小循环的性能问题