如何避免 append 函数修改底层数组?
时间:2023-04-30
浏览:173
作者:佚名
小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《如何避免 append 函数修改底层数组?》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!
问题内容
我使用 Go 语言编写数组所有组合的算法,例如:
输入
package main
import "fmt"
func main() {
res := subsets([]int{1, 2, 3, 4, 5})
fmt.Println("---")
for _, line := range res {
fmt.Println(line)
}
}
func subsets(nums []int) [][]int {
res := [][]int{{}}
n := len(nums)
combine(0, n, &nums, []int{}, &res)
return res
}
func combine(i, n int, nums *[]int, pre []int, res *[][]int) {
for ; i < n; i++ {
next := append(pre, (*nums)[i])
fmt.Println(next)
*res = append(*res, next)
combine(i+1, n, nums, next, res)
}
}
在第 25-27 行,我声明了一个
[1] [1 2] [1 2 3] [1 2 3 4] [1 2 3 4 5] [1 2 3 5] [1 2 4] [1 2 4 5] [1 2 5] [1 3] [1 3 4] [1 3 4 5] [1 3 5] [1 4] [1 4 5] [1 5] [2] [2 3] [2 3 4] [2 3 4 5] [2 3 5] [2 4] [2 4 5] [2 5] [3] [3 4] [3 4 5] [3 5] [4] [4 5] [5] --- [] [1] [1 2] [1 2 3] [1 2 3 5] [1 2 3 4 5] [1 2 3 5] [1 2 4] [1 2 4 5] [1 2 5] [1 3] [1 3 4] [1 3 4 5] [1 3 5] [1 4] [1 4 5] [1 5] [2] [2 3] [2 3 4] [2 3 4 5] [2 3 5] [2 4] [2 4 5] [2 5] [3] [3 4] [3 4 5] [3 5] [4] [4 5] [5]
为了查看方便,我将两次结果对比:

可以看到在第 4 行,两次输出结果不一致。我调试的时候发现,在插入
正确答案函数上,如文档介绍的:问题出在
append
The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is resliced to accommodate the new elements. If it does not, a new underlying array will be allocated. Append returns the updated slice...
只有当切片的底层数组有的容量不足时,才会分配新的底层数组。也就是说,使用
package main
import "fmt"
func main() {
a := []int{1,2,3,4,5}
fmt.Println(cap(a))
b := append(a, 6)
c := append(b[:2], 100)
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
}输出:
5 [1 2 3 4 5] [1 2 100 4 5 6] [1 2 100]
切片
next := make([]int, len(pre)) copy(next, pre) next = append(next, (*nums)[i])
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
