为什么要先将时间转换为字符串?您的目标应该是使用廉价的哈希函数广泛传播哈希值,对吗?这也是实时的吗?在这种情况下,你可以逃脱惩罚
unsigned short
对于成员。
#include <unordered_map>
#include <functional>
#include <string>
#include <iostream>
class Time {
public:
Time(unsigned short h = 0, unsigned short m = 0, unsigned short s = 0) :
hours(h), minutes(m), seconds(s) {}
bool operator==(Time const& other) const {
return (seconds==other.seconds &&
minutes==other.minutes &&
hours==other.hours);
}
unsigned short hours, minutes, seconds;
};
std::ostream& operator<<(std::ostream& o, Time const& t) {
o << t.hours << ":" << t.minutes << ":" << t.seconds;
return o;
}
namespace std {
template<> struct hash<Time> {
size_t operator()(Time const& t) const {
return size_t(((t.seconds * 37 + t.minutes) * 37 + t.hours) * 37);
}
};
}
int main() {
std::unordered_map<Time, std::string> u;
u[Time(3,15,31)] = std::string("Hello world");
u[Time(3,15,32)] = std::string("foo");
u[Time(3,15,32)] = std::string("bar");
for (auto const& i : u) {
std::cout << i.first << " - " << i.second << std::endl;
}
return 0;
}