所以我被告知要创建一个数组,该数组将从用户那里接受 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 pointers或 containers .
正确使用 C++ 语言并不需要您对大多数实际需要涵盖的用例使用new
/delete
。
关于c++ - 使用动态内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33903026/