因此,我被告知要创建一个数组,该数组将接受来自用户的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;
}
发布于 2015-11-25 04:21:52
应该使用运算符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
。
发布于 2015-11-25 04:32:15
动态内存管理应该使用smart pointers或containers提供的C++标准类和概念来完成。
正确使用C++语言并不要求您在实际需要涵盖的大多数用例中使用new
/delete
。
发布于 2019-04-23 03:19:04
要动态分配数组,您需要构建如下代码:
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 :)不反转您的原始表,而是以相反的方式提供assassin元素:
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。有几种方法可以做到这一点:)
https://stackoverflow.com/questions/33903026
复制相似问题