C++如何通过引用将数组传递给函数
C++ How to pass array by reference to function
这是我在学习C++时一直在做的事情的工作代码
我如何修改它,使ArraySortToMedian()使用指针表示法而不是数组表示法来处理数组?
到目前为止,我所有的尝试都没有奏效,所以我在逻辑关系或语法中缺少了一些东西。提前谢谢。
#include <iostream>
#include <fstream>
double ArraySortToMedian(int [], int );
using namespace std;
int main()
{
ifstream infile;
infile.open("numbers.txt");
const int SIZE = 6;
int array[SIZE];
int i = 0;
double median;
if(!infile)
{
cout << "couldn't find 'numbers.txt'";
return 1;
}
while(i < SIZE && infile >> array[i])
i++;
infile.close();
for(i = 0; i < SIZE; i++)
cout << *(array + i) << "!n";
median=ArraySortToMedian(array, SIZE);
cout<< "n" << median << "n";
return 0;
}
double ArraySortToMedian(int (x[]), int numElem)
{
bool swap;
int temp, i;
double m;
do
{
swap = false;
for(i = 0;i < (numElem - 1); i++)
{
if( x[i] > x[i + 1] )
{
temp = x[i];
x[i] = x[i + 1];
x[i + 1] = temp;
swap = true;
}
}
}
while (swap);
cout << "n";
for(i = 0; i < numElem; i++)
cout << x[i] << "n";
m = (x[numElem/2] + x[numElem/2]-1)/(double)2;
return(m);
}
您可以这样做。然而,我强烈建议您不要这样做,最好使用std::array
来获得更干净的实现。这样一个函数参数的语法非常难看。
使用原始C阵列
template <size_t N>
double ArraySortToMedian(int (&x)[N], int numElement);
使用STL阵列
template <size_t N>
double ArraySortToMedian(std::array<int,N>& x, int numElement)
这将不适用于动态分配的数组,如果您试图重载这些模板来处理指向用new
分配的数组的指针,则会变得非常复杂。
只需将签名更改为int* arr
,并使用*(x + i)
访问相关元素
相关文章:
- 第 i 个元素返回 i 的函数数组
- 使用嵌套函数数组是个好主意吗?
- 正确实现类函数数组
- 试图引用已删除函数数组的相等运算符
- 如何在静态函数中使用成员函数数组
- 无法创建函数数组
- 构造函数数组
- 使用开关或定义函数数组 - 更快
- 编写一个函数,该函数将覆盖主函数数组中的值
- 可以像'funs[1]();'一样调用的函数数组
- std::AVX内部函数数组
- 如果数组大小未知,如何将函数数组作为参数传递
- 从函数数组中获取值
- 使用元编程在编译时初始化函数数组
- 将C函数数组转换为C++函数指针数组
- 复制构造函数 [数组] C++
- 添加函数数组并随机选择其中一个
- 指针到私有成员函数数组
- 可以单独声明函数数组的元素
- (c++)将main中的随机值保存到函数数组中