📄 pex8_1.cpp
字号:
#include <iostream.h>
#include <stdlib.h>
#pragma hdrstop
#include "random.h"
#include "utils.h"
#include "wex8_3.h"
// "<" for two DynamicInt objects
int operator< (DynamicInt &a, DynamicInt &b)
{
// compare their values
return a.GetVal() < b.GetVal();
}
// generate a dynamic array of n DynamicInt objects having
// random values in the range 1..1000
DynamicInt *Initialize(int n)
{
// use one random sequence
static RandomNumber rnd;
// allocate a dynamic array of n objects,
// each with initial value 0
DynamicInt *p = new DynamicInt[n];
// if the memory allocation failed, terminate the program
if (p == NULL)
{
cerr << "Initialize: memor allocation failed!" << endl;
exit(1);
}
// reassign the object values to random integers in range 1..1000
for (int i = 0; i < n; i++)
p[i].SetVal(rnd.Random(1000) + 1);
// return address of the dynamic array
return p;
}
void main(void)
{
int n;
DynamicInt *p;
cout << "How many DynamicInt objects in the array? ";
cin >> n;
// create n objects with random values
p = Initialize(n);
// sort the array using the exchange sort. note that
// the "<" operator is used by the sort function
ExchangeSort(p,n);
// output the sorted objects
for (int i = 0; i < n; i++)
cout << p[i] << " ";
cout << endl;
}
/*
<Run>
How many DynamicInt objects in the array? 10
24 272 348 374 465 474 737 888 938 978
*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -