[英]unordered_map usage
class CTime
{
public:
CTime(){}
class valueComp
{
public:
bool operator()(const tm &A,const tm &B) const {
if ((A.tm_mday < B.tm_mday) && (A.tm_mon< B.tm_mon)&& (A.tm_year < B.tm_year) &&
(A.tm_hour< B.tm_hour)&& (A.tm_min< B.tm_min) && (A.tm_sec< B.tm_sec))
return true;
return false;
}
};
time_t MakeTime(struct tm *trf) {
if(HashTime.size()>86400)
HashTime.clear();
it =HashTime.find(*trf);
if( it == HashTime.end())
{ m_tDateSeconds= mktime (trf);
cout<<"mktime calculated"<<endl;
HashTime[*trf]= m_tDateSeconds;
return m_tDateSeconds;
}
else
{ cout<<"retrieving from map";
HashTime.find(*trf) ;
}}
private:
std::tr1::unordered_map<struct tm,long int,valueComp> HashTime;
std::tr1::unordered_map<struct tm,long int,valueComp>::iterator it;
time_t m_tDateSeconds;
};
int main()
{return 0;
}
这是我编写的代码,目的是检查无序地图是否对我有用?
如果代码中有任何错误,请告诉我,因为我是初学者。
unordered_map
是一个哈希表,因此,为了测试是否相等,还需要提供一个哈希函数。 标准库将为内置类型和其他一些类型(例如std::string
提供哈希函数,该函数用于unordered_map<std::string,int>
,但struct tm
不会提供一个哈希函数。所以你必须写一个。 这必须作为第三个模板参数提供---相等性测试是第四个参数,因此您需要unordered_map<struct tm,long,myHash,valueComp>
。
哈希函数必须是可调用的对象类型,其中函数调用运算符采用键类型的值并返回size_t
:
struct myHash{
size_t operator()(struct tm const&);
};
仅使用std::map<struct tm,long,compareTm>
(并编写排序比较compareTm
)可能比使用unordered_map
并提供良好的哈希函数要容易得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.