2017-09-27 8 views
0

私はこのようなクラスを持っています。cppのunordered_mapでカスタムクラスを使用

私は時間としてkeyを持つunordered_mapを使用したいと思います。これを行う良い方法は何ですか:

1)unordered_mapを使用します。ここで、文字列はクラスのフィールドの連結です。私は現在のユースケースに基づいて選択する助けてくださいhere

を議論のようなものを定義する)文字列に1とキー

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

あなたがしたいと思う理由:12:例えば、56を変換しますまず文字列に時間を変換しますか?あなたの目標は、安価なハッシュ関数を使ってハッシュ値を幅広く普及させることでしょうか?これもリアルタイムですか?その場合、あなたはメンバーのために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; 
} 
関連する問題