dsdtumf776629385 2014-02-25 18:58
浏览 35

前往:从地图弹出

Is there an existing function where we can pop a (key,value) pair from a map in GO? I use the word pop instead of remove because a pop would re-arrange the elements after the index where the (key,value) was removed.

As an example the following code:

package main

import "fmt"

func main() {
    mapp := make(map[int]int)
    fmt.Println("before removal:")

    for i := 1; i < 7; i++ {
        mapp[i] = i
    }
    fmt.Println(mapp)
    delete(mapp, 2)
    fmt.Println("
after the removal:")
    for i := 1; i < 7; i++ {
        fmt.Println(i, mapp[i])
    }

}

Produces the following output:

before removal:
map[1:1 2:2 3:3 4:4 5:5 6:6]

after the removal:
1 1
2 0
3 3
4 4
5 5
6 6

We notice that index location 2 is empty. I would like the output to be the following:

before removal:
map[1:1 2:2 3:3 4:4 5:5 6:6]

after the removal:
1 1
2 3
3 4
4 5
5 6

Is this functionality already in Go or would I have to implement it?

  • 写回答

2条回答 默认 最新

  • doushou1298 2014-02-25 19:11
    关注

    From the Go documentation:

    When iterating over a map with a range loop, the iteration order is not specified and is not guaranteed to be the same from one iteration to the next.

    From this, it follows that there would be no way to automatically move a value up one position to fill a gap, since the key can be in a different iteration position each time you look at the values and theres no guarantee that the value mapped to 2 will slide up to 1.

    If you want to do something like this, you will have to manually shift everything down one key value, something like:

    for key := 2; key < len(map)-1; key++ {
        map[key] = map[key+1]
    }
    

    Alternatively, you could use slices and if you know the index you need to "pop", create a new slice that omits the value:

    value := slice[2]
    slice = copy(slice[:2], slice[2+1:])
    
    评论

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码