【发布时间】: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