用new运算符动态分配一个长度为n的整型数组(n值由键盘输入),并给该数组随机赋上1—6的整数。然后用将该数组元素按从小到大排序,并输出。最后删除所申请空间。(C语言中stdlib.h、time.h在C++中要写成cstdlib、ctime)
//new -- allocate memory
#include <iostream>
using namespace std;
#include <cstdlib> //rand(), srand(), prototype
#include <ctime> //time() prototype
#include <algorithm> //sort() prototype
int main()
{
int n;
int *p;
//seed random-number generator
srand(time(0));
//input array size n
cout << "Enter the Array size: ";
cin >> n;
//allocate memory
p = new int[n+1];
//before sort
cout << "Before sort:" << endl;
for (int i = 0; i < n; i++)
{
*(p+i) = rand() % 6;
cout << *(p+i) << ", ";
}
cout << endl;
//please write sort function yourself
sort(p,p+n);
//After sort
cout << "After sort:" << endl;
for (int i = 0; i < n; i++)
{
cout << *(p+i) << ", ";
}
cout << endl;
//release memory
delete p;
return 0;
}
#include <iostream>
using namespace std;
#include <cstdlib> //rand(), srand(), prototype
#include <ctime> //time() prototype
#include <algorithm> //sort() prototype
int main()
{
int n;
int *p;
//seed random-number generator
srand(time(0));
//input array size n
cout << "Enter the Array size: ";
cin >> n;
//allocate memory
p = new int[n+1];
//before sort
cout << "Before sort:" << endl;
for (int i = 0; i < n; i++)
{
*(p+i) = rand() % 6;
cout << *(p+i) << ", ";
}
cout << endl;
//please write sort function yourself
sort(p,p+n);
//After sort
cout << "After sort:" << endl;
for (int i = 0; i < n; i++)
{
cout << *(p+i) << ", ";
}
cout << endl;
//release memory
delete p;
return 0;
}
温馨提示:答案为网友推荐,仅供参考