C++如何通过引用将数组传递给函数

C++ How to pass array by reference to function

本文关键字:函数 数组 何通过 引用 C++      更新时间:2023-10-16

这是我在学习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) 访问相关元素