在 cpp 中使用自定义 类 和 unordered_map

using custom classes with unordered_map in cpp

我有class这样的。

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

我想使用 unordered_map 键作为时间。这样做的更好方法是什么:

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

2) 定义类似讨论的内容 here

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

为什么要先将时间转换为字符串?您的目标应该是使用廉价的哈希函数广泛传播哈希值,对吗?这也是实时的?在这种情况下,您可以为成员免除 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;
}