c++ - 使用指针 C++ 创建一个临时数组

标签 c++ arrays pointers

我想知道这是否是在类中使用指针创建临时数组的正确方法。我的部分问题是这样说的:

getMedian – returns the median value of the array. See Chapter 10 Programming Challenge 6 (p. 693) for a discussion of the term median. Taking the median will require a sorted array. You will need to create a temporary array to sort the values (to preserve the ordering of numbers). Do not sort the private member numbers array. Dynamically allocate/deallocate a temporary array in your getMedian function to determine the median.

我的代码:

double Statistics::getMedian() const
{
    int tempArray[length];

    for (int k = 0; k < length; k++){
        tempArray[k] = numbers[k];
    }

    bubbleSort(tempArray);

    return 0;
}

显然在做中间部分和正确的 return 语句之前,是这样的。

你如何正确地复制一个临时数组来改变这个问题?我不认为这是因为我没有正确分配或取消分配任何东西,但我不明白如何在不改变原始数组的情况下创建临时数组。

最佳答案

你的作业说你要动态分配/取消分配数组。这意味着(在 C++ 中)使用 newdelete。既然你想要一个数组,你应该使用数组空间分配器运算符 new[]delete[] .

double Statistics::getMedian() const
{
    int *tempArray = new int[length];

    for (int k = 0; k < length; k++){
        tempArray[k] = numbers[k];
    }

    // work with tempArray

    delete[] tempArray;

    return 0;  // or the median
}

编辑: 正如下面评论中所建议的,现代(C++11 和更新版本)方法是使用 smart pointers .这意味着您的代码可能如下所示。

#include <memory>

double Statistics::getMedian() const
{
    std::unique_ptr<int[]> tempArray (new int[length]);

    for (int k = 0; k < length; k++){
        tempArray[k] = numbers[k];
    }

    // work with tempArray like you would with an old pointer

    return 0;  // or the median
    // no delete[], the array will deallocate automatically
}

检查 unique_ptr template class更多细节。请注意,此解决方案可能不是您的教授想要的,尤其是当作业涉及重新分配时。

关于c++ - 使用指针 C++ 创建一个临时数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36510665/

相关文章:

c++ - 仅当类有一个特定方法时如何调用?

java - 如何比较字符串数组并计算相似单词

arrays - 在 R 中写入和读取 3D 数组

c - 学习C - 编译错误分配指针

c++ - 使用私有(private)对象变量时如何稍后初始化数组(初始化对象后)

c++ - 对 QVariantMap 节点的优雅非常量引用?

c++ - 使用专门的模板并命名枚举选项

arrays - React 中的过滤器方法在 map 可用时不起作用

c++ - 为什么在 const 指针中进行非法结构操作?

pointers - 接受字符串引用的函数参数是否直接指向字符串变量或 Rust 堆上的数据