【发布时间】:2021-09-16 11:58:18
【问题描述】:
我需要使用冒泡排序对由Date 对象组成的数组进行排序。对象包含私有属性,所以我尝试使用友元函数。目前,程序正在运行,但打印的日期未排序,我猜在swap 和BubbleSortDates 函数中使用指针存在一些问题。我的代码如下。
#define N 10
#include <iostream>
using namespace std;
class Date;
bool compareDates(Date *date1, Date *date2);
class Date
{
// Data fields
int Year;
int Month;
int Day;
friend bool compareDates(Date *date1, Date *date2);
public:
Date(); // Constructor
Date(int YearIn, int MonthIn, int DayIn);
bool SetDate(int YearIn, int MonthIn, int DayIn);
void Print();
};
Date::Date()
{
Year = 1970;
Month = 1;
Day = 1;
}
Date::Date(int YearIn, int MonthIn, int DayIn)
{
bool IsValid = SetDate(YearIn, MonthIn, DayIn);
if (!IsValid)
{
Year = 1970;
Month = 1;
Day = 1;
}
}
bool Date::SetDate(int YearIn, int MonthIn, int DayIn)
{
if (YearIn <= 0 || MonthIn <= 0 || DayIn <= 0)
{
return false;
}
else
{
Year = YearIn;
Month = MonthIn;
Day = DayIn;
return true;
}
}
void Date::Print()
{
cout << "The day is: " << Day << "/" << Month << "/" << Year << endl;
}
bool compareDates(Date *date1, Date *date2)
{
if (date1->Year > date2->Year)
return true;
else if (date1->Year < date2->Year)
return false;
else
{
if (date1->Month > date2->Month)
return true;
else if (date1->Month < date2->Month)
return false;
else
{
if (date1->Year > date2->Year)
return true;
else if (date1->Year < date2->Year)
return false;
else
return true;
}
}
}
void swap(Date *xp, Date *yp)
{
Date temp = *xp;
*xp = *yp;
*yp = temp;
}
void BubbleSortDates(Date datesIn[])
{
for (int i = 0; i < N - 1; i++)
{
for (int j = 0; j < N - i - 1; j++)
{
Date *date1 = &datesIn[i];
Date *date2 = &datesIn[j];
if(compareDates(date1, date2))
{
swap(date1, date2);
}
}
}
for (int i = 0; i < N; i++)
{
datesIn[i].Print();
}
}
如何更正这些功能?提前致谢。
【问题讨论】:
-
+1,因为这是一个好问题。谦虚的建议:既然您有一个完整的代码(来自下面的好答案),请与 Stack Exchange 社区分享这个最终版本。您将收到有关如何添加您的代码当前缺乏的许多重要改进的指南。请不要误会我的意思。我真诚地只想在这里有建设性。
标签: c++ sorting for-loop oop bubble-sort