doumeng4400 2013-08-31 20:20
浏览 23
已采纳

在Go中合并两个数组…容器分配错误

I am trying to figure out what is wrong with my code all this morning but couldn't. It says it cannot assign containers. Please check this go play ground http://play.golang.org/p/RQmmi7nJAK

And the problematic code is below.

 func My_Merge(container []int, first_index int, mid_index int, last_index int) {
      left_array := make([]int, mid_index-first_index+1)
      right_array := make([]int, last_index-mid_index)
      temp_i := 0
      temp_j := 0

      for i := first_index; i < mid_index; i++ {
           left_array[temp_i] = container[i]
           temp_i++
      }

      for j := mid_index; j < last_index+1; j++ {
           right_array[temp_j] = container[j]
           temp_j++
      }

      i := 0
      j := 0

      for elem := first_index; elem < len(container); elem++ {
           if left_array[i] <= right_array[j] {
                container[elem] = left_array[i]
                i++
                if i == len(left_array) {
                     container[elem+1:last_index] = right_array[j:]
                     break              
                }           
           } else {
                container[elem] = right_array[j]
                j++
                if j == len(right_array) {
                     container[elem+1:last_index] = left_array[i:]
                     break              
                }
           }
      }
 }

I am getting the errors in the line container[elem+1:last_index] = right_array[j:]. Even if I delete the whole block, I am getting errors. Could anybody help me on this? I would greatly appreciate it.

  • 写回答

1条回答 默认 最新

  • douyimin1083 2013-08-31 21:19
    关注

    You can't assign to a slice expression in Go. You need to use copy:

    copy(container[elem+1:last_index], right_array[j:])
    

    But apparently there are other problems too, since when I change that in the playground I get an index out of range error.

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

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办