【问题标题】:Using Dynamic Memory Allocation使用动态内存分配
【发布时间】:2015-11-24 20:18:28
【问题描述】:

所以有人告诉我创建一个数组,该数组将接受来自用户的 10 个整数,将其存储到一个数组中,然后使用指针冒泡排序按升序对这些值进行排序。

我相信我已经成功完成了这么多,但我在第二部分遇到了麻烦。

“动态分配另一个10个整数数组。将元素从第一个复制到第二个,但顺序相反(即降序)。按顺序显示第一个和第二个数组的元素并释放动态分配的数组。”

我能够按顺序显示第一个数组,并且我知道要释放数组,您必须使用 delete 函数,但我不太确定如何构造动态数组。

*我没有包含这些功能,因为我不认为它们对于这部分是必需的,但是如果我这样做了,那么我也会发布它们。

提前感谢您的任何建议和澄清。

#include <iostream>

using namespace std;

void sortArray(int * , int);
void showArray(const int * , int);
int binarySearch(const int *, int, int);

int main(void)
{
    int const MAX_NUM = 10;
    int numbers [MAX_NUM];
    int counter;
    int findval;
    int index;
    char again;

    cout<< "Please enter 10 integer values."<< endl;
    for(counter=0; counter< MAX_NUM ; counter++)
    {
        cout << "Enter a value for "<< counter+1 << ": ";
        cin >> *(numbers+counter);
    }


    sortArray(numbers, 10);

    cout << endl << "The values in ascending order are: " << endl;
    showArray(numbers, 10);

    do
    {
        cout<< endl <<  "Enter the value you are searching for: ";
        cin >> findval; 
        cout << endl;
        index = binarySearch(numbers , MAX_NUM , findval);
        // Display the results of the search.
        if (index == -1)
            cout << "Number was not found." << endl << endl;
        else
            cout << "Number "<< findval<<" found in position " << index + 1 << endl << endl;
        // Does the user want to do this again?
        do
        {
            cout << "Would you like to look up another number? (y/n) ";
            cin >> again;
        }
        while(again != 'y' && again != 'Y' && again != 'n' && again != 'N');
    } 
    while (again == 'Y' || again == 'y');

    cout<< endl << "Thank You. Press the return key to continue...";

    cin.get();
    cin.ignore();
    return 0;   
}

【问题讨论】:

  • 这里没有动态分配任何东西!您的数组几乎是静态分配int numbers [MAX_NUM];
  • 我知道我不是,我不确定如何用我已经放在一起的东西来构造这个动态数组。
  • C++ 中的原始数组不是 动态数组(根据需要变大或变小),但可以动态分配(本质上 dynamic-arrays 标记不适合用于此目的question - 输入时检查标签的描述)。

标签: c++ arrays sorting dynamic-allocation


【解决方案1】:

应使用 smart pointerscontainers 提供的 C++ 标准类和概念来完成动态内存管理。

正确使用 C++ 语言并不要求您使用 new/delete 来处理您实际需要涵盖的大多数用例。

【讨论】:

  • 智能指针或容器是一个不错的选择,但有件事告诉我,这更像是一个学术练习,旨在展示对动态分配和释放内存的过程的理解。
  • @Derek 好吧,我不关心 academia 只要没有明确说明。我们已经有了这些机制,并且超越似乎毫无用处。我实际上讨厌学术界在正确使用可用的语言结构之前就试图教授这样的课程
  • @πάνταῥεῖ 10000% 同意。这就是为什么很多学生以错误的方式学习 C++,然后抱怨这门语言有多难和容易出错。讲师最终通过课程教授 C。现在已经不是 1981 年了。
【解决方案2】:

应该使用运算符new 来分配内存。对于解除分配,请使用delete

从分配内存开始:

    int * dynArr = NULL; // pointer to work with dynamic array
    dynArr = new int[MAX_NUM]; // allocation of memory

然后检查内存是否已分配,例如:

    if( dynArr != NULL )
    {
        // do something
    }
    else
    {
        // report about problem and do not use pointer
    }

并使用复制元素的功能,例如:

void reversCopy(const int * source, int * destination, int number)
// Function for copying numbers from one array (memory) to other 
// in the revers order (first element goes to the last position).
// source - pointer to array where numbers will be read
// destination - pointer to array where numbers will be written
// number - number of elements to be copyed
{ 
    for(int i = 0; i < number; i++)
    {
        destination[i] = source[number - 1 - i];
    }
}

最终,使用运算符释放动态内存:

  delete[] dynArr;
  dynArr = NULL;

之后不要使用dynArr

【讨论】:

  • 对于 C++ 中的数组,这不是完全正确的答案。
  • 更具体地说,对于数组,应使用new[] 分配内存,使用delete[] 释放内存。
  • @BaummitAugen 当然,但问题明确要求使用动态分配。
  • @AnkitAcharya 也许我被我巨大的智慧蒙蔽了双眼,使我无法移情,但是在 std::vector 之前教授动态分配的数组就是本末倒置。 std::vector 几乎是一劳永逸的,而数组处理中涉及的手动内存管理绝对不是我认为的基础。
  • @ElSpiffy 好吧,你的教授是个无知的笨蛋,并没有真正教 C++。不要这样,我建议告诉他们!
【解决方案3】:

要动态分配数组,您需要编写如下代码:

int *arr = new int[size];  // you have to remember to free memory when you won't need this array anymore - use delete[] achieve this

size 变量不必是 const 并且编译器在编译期间不需要知道它的值。您可以要求用户提供大小 :) 不要反转您的原始表格,只是以相反的方式刺客元素:

for (int i = 0; i < size; ++i)
{
    arr[i] = numbers[size - i - 1]; <-- '-1' to not read outside of orginal array (in C++ index starts with 0)
}

如果您想在不使用新表的情况下反转表,您应该访问:Reverse Contents in Array。有几种方法可以做到这一点:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 2013-07-01
    相关资源
    最近更新 更多