[英]How to correctly get value from unordered map?
我有這樣無序的地圖:
static std::unordered_map<std::pair<size_t , size_t>, long> my_map;
然后我想從my_map
獲取價值:
size_t size1 = 1;
size_t size2 = 2;
auto x = make_pair(size1, size2);
auto &result = my_map[x];
但是我有一個錯誤:
error: no match for ‘operator[]’ (operand types are ‘std::unordered_map<std::pair<long unsigned int, long unsigned int>, long int>’ and ‘std::pair<long unsigned int, long unsigned int>’)
auto &result = my_map[x];
我怎么能克服它?
使用此處的哈希函數:
#include <unordered_map>
#include <utility>
#include <map>
#include <functional>
#include <string>
// Only for pairs of std::hash-able types for simplicity.
// You can of course template this struct to allow other hash functions
struct pair_hash {
template <class T1, class T2>
std::size_t operator () (const std::pair<T1, T2> &p) const {
auto h1 = std::hash<T1>{}(p.first);
auto h2 = std::hash<T2>{}(p.second);
// Mainly for demonstration purposes, i.e. works but is overly simple
// In the real world, use sth. like boost.hash_combine
return h1 ^ h2;
}
};
int main()
{
//static std::unordered_map<std::pair<size_t, size_t>, long> my_map;
static std::unordered_map<std::pair<size_t, size_t>, long, pair_hash> my_map;
size_t size1 = 1;
size_t size2 = 2;
auto x = std::make_pair(size1, size2);
auto &result = my_map[x];
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.