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 outlook无法配置成功
  • ¥15 Pwm双极模式H桥驱动控制电机
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换