首页 > 解决方案 > 通过引用函数传递数组

问题描述

我需要帮助通过引用将数组传递给函数。数组是预先创建的,并被传递给函数,但通过函数后数组的值不是我想要的 - 它保持不变。代码如下所示。函数是取一个数组,一个位置 p 和一个值 val。假定数组按升序排序直到位置 p 并且值 val 必须放置使得数组按升序排序直到位置 p+1。

#include <iostream>
using namespace std;

// Function that takes an array a, a position,
// and a float value val to insert.
// a must already be sorted in acsending order
// up to p. val is then inserted such that
// the a is sorted up to p+1.
// p = 0 means position a[0].
void insert(double (&a)[], int aSize, int p, double val)
{
    try {
        // Throw error if p > size of array
        if(p > aSize || p < 0) {
            throw logic_error("Position is greater than size of array or less than zero.");
        }

        int newSize = aSize + 1;
        double* vTemp = new double[newSize]; // create new bigger array
        for(int i = 0; i <= p; i++) {
            if(val >= a[i]) {
                vTemp[i] = a[i];
            } else {
                vTemp[i] = val;
                for(int j = i + 1; j < newSize; j++) {
                    vTemp[j] = a[j - 1];
                }
                break;
            }
        }
        cout << "Size of vTemp = " << newSize << endl;
        for (int k = 0; k < newSize; k++){
            cout << "vTemp[" << k << "] = " << vTemp[k] << endl;
        }
        a = vTemp;
        delete[] vTemp;

    } catch(const logic_error& e) {
        cout << "Error in input: " << e.what() << endl;
    }
}

int main()
{
    // Declare variables
    double myArray[] = { 1, 2, 4, 8, 16, 20, 50, 30, 153 }; // sample array to test function
    int p = 5;                                              // position
    double val = 7.2;                                       // value to insert
    int arraySize = sizeof(myArray) / sizeof(myArray[0]);   // no. of elements in array
    int newSize = 0;                                        // size of expanded matrix

    // Insert val
    insert(myArray, arraySize, p, val);
    cout << "Size of original array: " << arraySize << endl;

    // Display new expanded matrix
    newSize = sizeof(myArray) / sizeof(myArray[0]); // size of expanded matrix
    cout << "Size of expanded array: " << newSize << endl << endl;

    for(int i = 0; i < newSize; i++) {
        cout << myArray[i] << " ";
    }
    cout << endl;

    // Return success
    return 0;
}

标签: c++function

解决方案


不要使用原始数组。您正在寻找的课程被称为std::vector参考)。

只需创建一个向量而不是数组并通过引用传递它,您就可以获得所需的内容。


推荐阅读