麻烦大家帮忙看一下是哪里的问题,跑不出来
具体应该怎么改呢
#include
#include
#include
using namespace std;
class Clock {
private:
int h;
int m;
int s;
int zone; // 范围[-12, 12] 例如 中国为+8
public:
Clock() {
h = rand() % 25;
m = rand() % 61;
s = rand() % 61;
zone = (rand() % 25) - 12;
};
int geth() { return h + zone; }
int getm() { return m; }
int gets() { return s; }
};
bool compare(Clock& c1, Clock& c2) {
if (c1.geth() > c2.geth()) {
return true;
}
else if (c1.getm() > c2.getm()) {
return true;
}
else if (c1.getm() > c2.gets()) {
return true;
}
else
return false;
}
void show(Clock& elem) {
cout << "h:" << elem.geth() << "\t" << "m:" << elem.getm() << "\t" << "s:" << elem.gets() << endl;
}
int main() {
// 初始化随机种子
srand((unsigned)time(NULL));
const int count = 20;
// 定义 count 个Clock对象,其h, m, s, zone均由随机生成
Clock* elem = new Clock[count];
// rand()函数 随机生成 0 到无穷 之间的一个整数
Clock* cs[count];
// 对 count个Clock按格林威治标准时间按升序排序
for (int i = 0; i < count; i++) {
for (int j = 0; j < count - i; j++) {
if (compare(elem[j], elem[j + 1]) == true) {
*cs = elem[j];
elem[j] = elem[j + 1];
elem[j + 1] = *cs;
}
}
}
// 显示排序后的结果
for (int i = 0; i < count; i++)
{
show(elem[i]);
}
// 释放动态数组空间
for (int i = 0; i < count; i++)
{
free(&elem[i]);
}
return 0;
}
for (int i = 0; i < count-1; i++) {
for (int j = 0; j < count - i-1; j++) {
这里必须j<count-i-1,否则i=0时,j就可以是count-1,那么elem[j+1]就越界了