dthjnc306679 2014-05-05 22:13
浏览 75

从地图获取任意键/项目

I am new to Go and now I want to get an arbitrary item from a map; what's the idiomatic way to do that? I can only think of something like this:

func get_some_key(m map[int]int) int {
    for k := range m {
        return k
    }
    return 0
}

The reason I want that is I am using a map to maintain a set of jobs, and with a map I can get a pending job or remove a finished job in O(1). I guess this should be a common requirement but it's not obvious how to do it in Go.

  • 写回答

3条回答 默认 最新

  • doujuanxun7167 2014-05-05 22:36
    关注

    Whether getting an arbitrary key from a hash table is a common requirement may be discussed. Other language map implementations often lack this feature (eg. Dictionary in C# )

    However, your solution is probably the fastest one, but you will be left with a pseudo-random algorithm that you do not control. And while the current implementation uses a pseudo-random algorithm, the Go Specification doesn't give you any assurance it will actually be random, only that it is not guaranteed to be predictable:

    The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next.

    If you want more control of the randomization, you can also in parallel keep an updated slice of values (or keys) contained in the map, using the randomization of your choice (math/rand or crypto/rand for more extreme cases) to get the value stored at an index, selected randomly, in the slice.

    评论

报告相同问题?

悬赏问题

  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私