相关疑难解决方法(0)

使用自定义类类型作为键的C++ unordered_map

我正在尝试使用自定义类作为关键字unordered_map,如下所示:

#include <iostream>
#include <algorithm>
#include <unordered_map>

using namespace std;

class node;
class Solution;

class Node {
public:
    int a;
    int b; 
    int c;
    Node(){}
    Node(vector<int> v) {
        sort(v.begin(), v.end());
        a = v[0];       
        b = v[1];       
        c = v[2];       
    }

    bool operator==(Node i) {
        if ( i.a==this->a && i.b==this->b &&i.c==this->c ) {
            return true;
        } else {
            return false;
        }
    }
};

int main() {
    unordered_map<Node, int> m;    

    vector<int> v;
    v.push_back(3);
    v.push_back(8);
    v.push_back(9);
    Node n(v);

    m[n] = 0; …
Run Code Online (Sandbox Code Playgroud)

c++ hash unordered-map g++ hashtree

258
推荐指数
3
解决办法
22万
查看次数

为什么没有C ++ POD结构的默认哈希?

我想将POD结构用作地图中的哈希键,例如

struct A { int x; int y; };
std::unordered_map<A, int> my_map;
Run Code Online (Sandbox Code Playgroud)

但我不能这样做,因为没有哈希函数可自动为此类结构生成。

  • 为什么C ++标准不需要POD结构的默认哈希?
  • 为什么即使标准没有强制要求,编译器(特别是GCC 4.x / 5.x)也提供这样的哈希值?
  • 如何使用模板以可移植的方式为我的所有POD结构生成哈希函数(如果需要,我愿意做出语义假设)?

c++ hash templates struct unordered-map

5
推荐指数
1
解决办法
1498
查看次数

为 CString 创建 unordered_map 作为 key

我正在尝试创建以下 unordered_map:

std::unordered_map<CString, CString, std::function<size_t(const CString &data)>> usetResponse(100, [](const CString &data)
    {
        return std::hash<std::string>()((LPCSTR)data);
    });
Run Code Online (Sandbox Code Playgroud)

我为 CString 提供了哈希函数,但编译器仍然返回错误:

error C2338: The C++ Standard doesn't provide a hash for this type. 

error C2664: 'std::unordered_map<CString,CString,std::hash<_Kty>,std::equal_to<_Kty>,std::allocator<std::pair<const
_Kty,_Ty>>>::unordered_map(std::initializer_list<std::pair<const _Kty,_Ty>>,unsigned int,const std::hash<_Kty> &,const _Keyeq &,const std::allocator<std::pair<const _Kty,_Ty>> &)' : cannot convert argument 1 from 'std::unordered_map<CString,CString,std::function<size_t (const CString &)>,std::equal_to<_Kty>,std::allocator<std::pair<const
_Kty,_Ty>>>' to 'const std::unordered_map<CString,CString,std::hash<_Kty>,std::equal_to<_Kty>,std::allocator<std::pair<const
_Kty,_Ty>>> &'
Run Code Online (Sandbox Code Playgroud)

请告诉我我做错了什么?

c++ mfc unordered-map

4
推荐指数
1
解决办法
2033
查看次数

标签 统计

c++ ×3

unordered-map ×3

hash ×2

g++ ×1

hashtree ×1

mfc ×1

struct ×1

templates ×1