英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论