duanjiani6826 2018-09-15 20:18
浏览 77
已采纳

如何在Golang中为哈希图制作复合键

First, my definition of composite key - two ore more values combine to make the key. Not to confuse with composite keys in databases.

My goal is to save computed values of pow(x, y) in a hash table (x and y are integers). This is where I need ideas on how to make a key, so that given x and y, I can look it up in the hash table, to find pow(x,y).

Eg. pow(2, 3) => {key(2,3):8} Function / way to get the key(2,3) is what I want to figure out.

In general whats the best way to handle key which is a combination of multiple values, while using as a key in hash table.

Thanks

  • 写回答

2条回答 默认 最新

  • douran7929 2018-09-15 20:42
    关注

    The easiest and most flexible way is to use a struct as the key type, including all the data you want to be part of the key, so in your case:

    type Key struct {
        X, Y int
    }
    

    And that's all. Using it:

    m := map[Key]int{}
    m[Key{2, 2}] = 4
    m[Key{2, 3}] = 8
    
    fmt.Println("2^2 = ", m[Key{2, 2}])
    fmt.Println("2^3 = ", m[Key{2, 3}])
    

    Output (try it on the Go Playground):

    2^2 =  4
    2^3 =  8
    

    Spec: Map types: You may use any types as the key where the comparison operators == and != are fully defined, and the above Key struct type fulfills this.

    Spec: Comparison operators: Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.

    One important thing: you should not use a pointer as the key type (e.g. *Key), because comparing pointers only compares the memory address, and not the pointed values.

    Also note that you could also use arrays (not slices) as key type, but arrays are not as flexible as structs. You can read more about this here: Why have arrays in Go?

    This is how it would look like with arrays:

    type Key [2]int
    
    m := map[Key]int{}
    m[Key{2, 2}] = 4
    m[Key{2, 3}] = 8
    
    fmt.Println("2^2 = ", m[Key{2, 2}])
    fmt.Println("2^3 = ", m[Key{2, 3}])
    

    Output is the same. Try it on the Go Playground.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 数据库数据成问号了,前台查询正常,数据库查询是?号
  • ¥15 算法使用了tf-idf,用手肘图确定k值确定不了,第四轮廓系数又太小才有0.006088746097507285,如何解决?(相关搜索:数据处理)
  • ¥15 彩灯控制电路,会的加我QQ1482956179
  • ¥200 相机拍直接转存到电脑上 立拍立穿无线局域网传
  • ¥15 (关键词-电路设计)
  • ¥15 如何解决MIPS计算是否溢出
  • ¥15 vue中我代理了iframe,iframe却走的是路由,没有显示该显示的网站,这个该如何处理
  • ¥15 操作系统相关算法中while();的含义
  • ¥15 CNVcaller安装后无法找到文件
  • ¥15 visual studio2022中文乱码无法解决