을 기반으로 선택합니다 도와주세요 먼저 시간을 문자열로 변환 하시겠습니까? 당신의 목표는 값싼 해시 함수를 사용하여 해시 값을 널리 퍼뜨려 야합니다. 맞습니까? 또한 이것은 실시간입니까? 어떤 경우에는 회원들에게 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;
}
확실히 (2). (1)은 느리고 좋지 않습니다. – HolyBlackCat
클래스 정의를 수정할 수 없습니다. 여전히 방법 2를 사용할 수 있습니까? – crystal
예. 클래스를 변경하여 (링크가 보여 주듯이)'std :: hash'를 전문으로 할 필요가 없으며 [std :: equal_to'를 전문으로 할 수 있습니다 (http://en.cppreference.com/w/cpp/utility/functional/equal_to) 대신에'=='을 오버로딩 할 수 있습니다. – HolyBlackCat