在给定索引的切片中插入值 [英] Insert a value in a slice at a given index
问题描述
给予
array1 := []int{1, 3, 4, 5}
array2 := []int{2, 4, 6, 8}
我想在 array1 [1]
即 3
之前插入 array2 [2]
即 6
array1
变成 {1、6、3、4、5}
的一部分.我该怎么办?
I want to insert array2[2]
i.e 6
at array1[1]
i.e before 3
so that array1
becomes a slice of {1, 6, 3, 4, 5}
. How can I do it?
我在线阅读的大多数技术都涉及到使用:
运算符,但也会导致剩余元素也被插入.如何在切片的索引处附加单个值?
Most the techniques I read online involve using the :
operator but results in remaining elements being inserted as well. How can I append single values at an index in a slice?
推荐答案
简单,高效且合乎逻辑的方式:
Simple, efficient and logical way:
- 确保
array1
具有足够的容量(长度)以容纳新的可插入元素.为此,请使用内置的append()
(这无关紧要,它将被覆盖). - 要插入元素,必须对现有元素进行移位(复制到更高的1个索引)以为该元素腾出空间,例如使用内置的
copy()
(要插入的元素). - 使用单个分配将元素设置为正确的索引.
- Make sure
array1
has enough capacity (length) to accomodate the new, insertable element. To do that, append a single element using the builtingappend()
(doesn't matter what that is, it'll get overwritten). - To insert an element, existing elements must be shifted (copied over to 1 index higher) to make room for that element, e.g. using the builtin
copy()
(elements you want to insert before). - Set the element at the proper index, using a single assignment.
在代码中:
array1 := []int{1, 3, 4, 5}
array2 := []int{2, 4, 6, 8}
array1 = append(array1, 0) // Step 1
copy(array1[2:], array1[1:]) // Step 2
array1[1] = array2[2] // Step 3
fmt.Println(array1)
输出(在转到游乐场上尝试):
[1 6 3 4 5]
特殊情况下的优化
请注意,在某些特殊情况下(当slice元素很大时,就像一个大结构),附加最后一个元素可能会更快,然后复制少于1个元素就足够了(因为附加的最后一个元素是正确的的位置.
Optimization in special cases
Note that in some special cases (when the slice element is big, like a big struct), it may be faster to append the last element, and then it's enough to copy 1 less elements (because the appended last element is right where it needs to be).
它是这样的:
last := len(array1) - 1
array1 = append(array1, array1[last]) // Step 1
copy(array1[2:], array1[1:last]) // Step 2
array1[1] = array2[2] // Step 3
这将导致相同的切片.在去游乐场上尝试一下.
This will result in the same slice. Try this one on the Go Playground.
这篇关于在给定索引的切片中插入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!