2017-09-27 4 views
0

클래스가 있습니다.cpp에서 unordered_map이있는 사용자 정의 클래스 사용

key와 함께 시간대로 unordered_map을 사용하고 싶습니다. 이 작업을 수행하는 더 좋은 방법은 무엇입니까?

1) string은 class 필드의 연결입니다. 12 : : 예는 56 변환 문자열에 1을 논의 here

같은이 같은 주요

2) 정의 뭔가를 사용하여 당신이 원하는 것이 왜 나를이 현재 사용 사례 :

+1

확실히 (2). (1)은 느리고 좋지 않습니다. – HolyBlackCat

+0

클래스 정의를 수정할 수 없습니다. 여전히 방법 2를 사용할 수 있습니까? – crystal

+1

예. 클래스를 변경하여 (링크가 보여 주듯이)'std :: hash'를 전문으로 할 필요가 없으며 [std :: equal_to'를 전문으로 할 수 있습니다 (http://en.cppreference.com/w/cpp/utility/functional/equal_to) 대신에'=='을 오버로딩 할 수 있습니다. – HolyBlackCat

답변

1

을 기반으로 선택합니다 도와주세요 먼저 시간을 문자열로 변환 하시겠습니까? 당신의 목표는 값싼 해시 함수를 사용하여 해시 값을 널리 퍼뜨려 야합니다. 맞습니까? 또한 이것은 실시간입니까? 어떤 경우에는 회원들에게 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; 
}