1. 程式人生 > >C++ map以自定義資料型別做鍵值

C++ map以自定義資料型別做鍵值

struct Time
{
	UINT16 nYear;
	UINT8 nMonth;
	UINT8 nDay;
	UINT8 nHour;
	UINT8 nMinute;
	UINT8 nSecond;
	UINT16 nTick;
	Time()
	{

	}
	Time(UINT16 nYear,UINT8 nMonth,UINT8 nDay,UINT8 nHour,UINT8 nMinute,UINT8 nSecond,UINT16 nTick)
	{
		this->nYear = nYear;
		this->nMonth = nMonth;
		this->nDay = nDay;
		this->nHour = nHour;
		this->nMinute = nMinute;
		this->nSecond = nSecond;
		this->nTick = nTick;
	}
	Time(const Time &stTime)
	{
		*this = stTime;
	}
	bool operator<(const Time& stTime) const
	{
		//比較年
		if (this->nYear < stTime.nYear)
		{
			return true;
		}
		else if (this->nYear == stTime.nYear)
		{
			//比較月份
			if (this->nMonth < stTime.nMonth)
			{
				return true;
			}
			else if (this->nMonth == stTime.nMonth)
			{
				//比較day
				if (this->nDay < stTime.nDay)
				{
					return true;
				} 
				else if (this->nDay == stTime.nDay)
				{
					//比較nHour
					if (this->nHour < stTime.nHour)
					{
						return true;
					}
					else if(this->nHour == stTime.nHour)
					{
						//比較分鐘
						if (this->nMinute < stTime.nMinute)
						{
							return true;
						}
						else if (this->nMinute == stTime.nMinute)
						{
							if (this->nSecond < stTime.nSecond)
							{
								return true;
							}
							else if (this->nSecond == stTime.nSecond)
							{
								if (this->nTick < stTime.nTick)
								{
									return true;
								}
								else
								{
									return false;
								}
							}
							else
							{
								return false;
							}
						}
						else
						{
							return false;
						}
					}
					else
					{
						return false;
					}
				}
				else
				{
					return false;
				}
			}
			else
			{
				return false;
			}
		}
		else
		{
			return false;
		}
	}
};
typedef map<Time,string> TMap;

測試程式碼: