gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:44:21 27 4
gpt4 key购买 nike

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

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com