gpt4 book ai didi

c++ - 如何正确地从无序 map 中获取值(value)?

转载 作者:太空宇宙 更新时间:2023-11-04 13:10:38 26 4
gpt4 key购买 nike

我有这样的无序 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];

我怎样才能克服它?

最佳答案

使用 here 中的哈希函数:

#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;

}

关于c++ - 如何正确地从无序 map 中获取值(value)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40117207/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com