追加新行到多维切片中

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

Append new row to multidimensional slice

问题

我有一个创建2D切片的函数,其中有一行和三列。

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

如果我想动态添加一行怎么办?

如果result只是一个普通的切片,我可以直接在切片的末尾添加,但是对于2D数组,似乎我需要手动做很多事情,有没有更简单的方法?

编辑:我自己的做法是,如果我需要添加一行:

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

事后看来这并不是坏方法 追加新行到多维切片中 如果有人有意见,我很乐意接受。

英文:

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

得分: 0

你的翻译如下:

你展示的方式确实是应该这样做的,当然这是最简单的方式...

有一种方法可以使用copy来做,但这需要你手动分配一个新的切片,所以通常会更慢,并且在每种情况下都需要更多的代码。

如果你需要在现有列的中间或开头添加一个新列,那么你需要分配一个新的切片(或者如果你当前的切片有未使用的空间,则增加其长度),将旧切片的元素复制到新切片中(通过两个操作,使得你需要的插入位置为空),最后直接添加新的元素。这至少需要3行代码,在最紧凑的情况下,如果包含边界检查和可选的高效路径,则需要更多行。

英文:

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.

huangapple
  • 本文由 发表于 2017年9月4日 21:13:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/46037883.html
匿名

发表评论

匿名网友

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

确定