定义具有任意维度键的映射。

huangapple go评论92阅读模式
英文:

Define map with keys with arbitrary dimension

问题

以下代码用于为每对float64创建一个计数器。
由于映射的键不能是切片,我必须使用数组作为键,这迫使我使用常量定义一个维度。

counter := make(map[[2]float64]int)
for _, comb := range combinations { // combinations是一个[n][2]float64
for _, row := range data {
counter[[...]float64{row[comb[0]], row[comb1]}]++
}
}

话虽如此,有没有办法使这个映射依赖于键的长度(取决于combinations的维度)?
我尝试使用结构体作为键,但据我记得(我可能记错了),它速度有点慢... 对于我的目的(将其应用于所有组合~n!),这不是理想的解决方案。

现在我只考虑大小为2和3的组合,并且我不得不将其拆分为两个单独的函数,这使得我的代码非常冗长且难以维护。
你能找到简化这个问题的方法,以便我可以将其扩展到更多维度吗?

感谢任何建议。

英文:

The following code serves to create a counter for each pair of float64.
Because the keys of a map cannot be a slice, I have to use arrays as keys, which forces me to to define a dimension with a constant.

counter := make( map[ [2]float64 ] int )
for _, comb := range combinations{ //combinations is a [n][2]float64
    for _, row := range data{  
        counter[ [...]float64{ row[comb[0]] , row[comb[1]] } ]++
    }
}

Having said that, is there a way to make this map dependent on the length of the keys (dependent on the dimensions of combinations?
I tried using a struct as key, but as far as I remember (I might be wrong), it was a bit slower... For my purposes (to apply this for all combinations ~n!) this is not the ideal solution.

Right now I'm only considering combinations of size 2 and 3, and I had to split this in two separate functions, which makes my code very verbose and harder to maintain.
Can you find a way to simplify this, so I can scale it to more dimensions?

Thanks for any input

答案1

得分: 1

为什么不使用切片的指针作为键?

你可以使用make创建一个容量足够大的切片,只要不超过其容量,指针就会保持不变。

在这里查看示例:https://play.golang.org/p/333tRMpBLv,它展示了我的建议。注意,只有在长度超过容量时,append才会创建一个新的切片,否则切片的指针不会改变。

英文:

Why not use the pointer to a slice as key?

You could create a slice with make with a big enough capacity, while you do not surpass it's capacity, the pointer will remain the same.

Take a look here https://play.golang.org/p/333tRMpBLv , it exemplifies my suggestion. see that while len < cap the pointer of the slice is not changed, append only creates a new slice when len exceeds cap.

huangapple
  • 本文由 发表于 2017年7月10日 17:22:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/45008274.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定