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 如何实验stm32主通道和互补通道独立输出
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题