在cpp中使用带有unordered_map的自定义类

时间:2017-09-27 16:37:26

标签: c++ unordered-map

我有这样的课。

class Time
{
  public:
    int seconds, minutes, hours;
};

我想使用带有键的unordered_map作为Time。有什么更好的方法:

1)使用unordered_map,其中string是类字段的串联。例如,将56:12:1转换为字符串并将其用作键

2)定义类似于讨论here

的内容

请根据当前用例帮我选择:)

1 个答案:

答案 0 :(得分: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;
}