doulun0651 2019-05-22 00:32
浏览 44
已采纳

附加到二维字符串切片时的奇怪行为

This question already has an answer here:

I'm attempting to implement Heap's Permutation Algorithm in Go. It's supposed to return all the possible permutations given an input set.

func Permute(in []string) [][]string {
    c := make([]int, len(in))
    out := make([][]string, 0)
    for i := range out {
        out[i] = make([]string, 0)
    }
    fmt.Println(in)
    out = append(out, in)
    i := 0
    for i < len(in) {
        if c[i] < i {
            if i%2 == 0 {
                in[0], in[i] = in[i], in[0]
            } else {
                in[c[i]], in[i] = in[i], in[c[i]]
            }
            fmt.Println(in)
            out = append(out, in)
            c[i]++
            i = 0
        } else {
            c[i] = 0
            i++
        }
    }
    return out
}

The Println statements display the expected outputs. The out value is returned with the correct number of entries, but the entries are all the same. Please help me understand what I am missing.

</div>
  • 写回答

1条回答 默认 最新

  • douzheyo2617 2019-05-22 01:26
    关注

    The value of in is never changed, so every element in out has that same value. in contains the slice header, which is a pointer to the underlying array, a length, and a capacity. You're changing the values in the array, but the slice header remains the same. I think you want to make a copy of in inside the for loop so you're operating on a different array every time:

    for i < len(in) {
        inCopy := make([]string, len(in))
        copy(inCopy, in)
        in = inCopy
        // ...
    }
    

    See https://blog.golang.org/go-slices-usage-and-internals for an explanation of how slices work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥15 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)