dqhgjay5753 2017-09-04 13:13
浏览 31
已采纳

将新行追加到多维切片

I have a function which creates a 2d slice, one row and three columns

func threeSum(nums []int) [][]int {
    result := make([][]int, 1)
    result[0] = []int{1, 2, 3}
    return result
}

What if I want to dynamically add a row?

If result was just a normal slice I would just append to the end of the slice, however with the 2d array it seems I have to manually do a lot of things, is there an easier way?

EDIT: My way of doing it would be, if I need to add a new row:

result = append(result, []int{4, 2, 3})

Which in hindsight isn't actually bad :) If anyone has an opinion I'll be happy to accept.

  • 写回答

1条回答 默认 最新

  • dongqiuqiu4736 2017-09-04 14:57
    关注

    The way you present is indeed how it should be done, certainly it is the easiest way...

    There is a way to do it with copy, but that would require you to manually alocate a new slice, so it would often be far slower, and in every case it would require more code.

    If you need to add a new column in the middle or at the beginning of the existing ones, then you will need to alocate a new slice (or, if your current slice has unused space, increases it's length), copy the elements from the old slice to the new slice (in two operations so the slot you need for your new item is left empty), and finaly add your new item directly. This takes a minimum of 3 lines of code in the most compact case, more with bounds checking and optional higher efficency paths.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)