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条)

报告相同问题?

悬赏问题

  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan