在unordered_map中插入元素会产生错误

mah*_*ood 0 c++ unordered-map vector

我已经定义了unordered_map这样的

struct pht {
  pht(int t, vector<bool> pat) 
: tag(t), pattern(32) {}
private:
  int tag;
  vector<bool> pattern;
};

unordered_map< pair<int, int>, pht > predictor;

int main()
{
  int pc, addr, offset, tag;
  vector<bool> pat;
  srand(time(0));

  tag = 1000; pc = 100; offset = 10; 
  for ( int i = 0; i < 32; i++ ) 
  pat.push_back( rand() % 2 );
  predictor.insert(make_pair( make_pair(pc, offset), pht(tag, pat) ) );
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是我收到此错误:

(更新)

error C2440: 'type cast' : cannot convert from 'const std::pair<_Ty1,_Ty2>' to 'size_t' 
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

Kon*_*lph 5

错误消息具有误导性; 真正的原因是没有std::hash专业化std::pair<int, int>要求unordered_map.您需要提供此专业化或(推荐)创建一个unordered_map指定自定义哈希:

struct hash_pair {
    template <typename T, typename U>
    std::size_t operator ()(std::pair<T, U> const& p) const {
        using std::hash;
        return hash<T>()(p.first) ^ hash<T>()(p.second);
    }
};
Run Code Online (Sandbox Code Playgroud)

然后将地图声明为:

unordered_map<pair<int, int>, pht, hash_pair> predictor;
Run Code Online (Sandbox Code Playgroud)

  • 我推荐[带模板`operator()`的非模板谓词)(http://ideone.com/qgNUtE) (2认同)