c++ - 使用动态内存分配

标签 c++ arrays sorting dynamic-allocation

所以我被告知要创建一个数组,该数组将从用户那里接受 10 个整数,将其存储到一个数组中,然后使用指针冒泡排序对这些值进行升序排序。

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

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

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

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

提前感谢您的任何建议和说明。

#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;   
}

最佳答案

动态内存管理应该使用可用的 C++ 标准类和概念来完成 smart pointerscontainers .

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

关于c++ - 使用动态内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33903026/

相关文章:

ruby-on-rails - 如何在 Ruby 中对世界杯小组赛表进行排序

sorting - CoreData 维护关系顺序

c++ - 使用 C++ GSOAP 客户端访问 Amazon S3 服务

c++ - Qt的两个QList成员变量导致崩溃

PHP 从保留先前键的数组中提取部分

javascript - 在对象数组中搜索对象

JavaScript 数组 : is there a method that is a cross between splice and filter?

c++ - 给定指向节点的指针,删除该特定节点

c++ - 避免缩小 bitset 模板的转换

python - 对导入的列表进行排序不起作用