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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀