【发布时间】:2016-02-22 19:47:14
【问题描述】:
我希望有一个数据结构(数组或切片)看起来像这样:
[[a b c d e][f g h i j] [k l m n o] [p q r s t] [u v w x y]]
使得 a 是节点从 "A" 到 "A" 的距离。 (应为 0) b 是节点从 "A" 到 "B" 的距离。 c 是节点从“A”到“C”的距离。
f 是节点从 "B" 到 "A" 的距离。 g 是节点从 "B" 到 "B" 的距离。 (应为 0) h 是节点从“B”到“C”的距离。
现在我创建了一个像这样的切片:
var shortestPathSLice = make([][]int, 5) 存储此二维数据。
在函数内的 for 循环中,我尝试如下动态填充此切片:
shortestPathSLice = append(shortestPathSLice[0][index], lowEstimate[0])
其中 minimumimate[0] 是两个节点之间的最小距离值。
但是,我得到一个错误:第一个参数 append 必须是 slice;有int
谁能告诉我如何在切片的每个元素中动态附加值?
**代码**
var shortestPathSLice = make([][]int, 5)
for index := 0; index < len(t.Location_ids); index++ {
lowEstimate := make([]int, len(priceestimatestruct.Prices))
for i := 0; i < len(priceestimatestruct.Prices); i++ {
lowEstimate[i] = priceestimatestruct.Prices[i].LowEstimate
}
sort.Ints(lowEstimate)
fmt.Println("LowEstimate array : ", lowEstimate)
shortestPathSLice[0] = make([]int, len(lowEstimate))
shortestPathSLice[0][index] = lowEstimate[0]
}
【问题讨论】:
-
shortestPathSLice是一个[][]int类型的二维数组。所以shortestPathSLice[0][index]选择0.index处的int。但是,追加的第一个 arg 必须是切片,因此您的0或index应省略。 -
我认为您要做的是:
shortestPathSLice[0][index] = lowEstimate[0]。那将分配int?lowEstimate[0]切片索引0.index. -
@RickyA 感谢您的回复。对于第一次迭代,我的 LowEstimate 数组是:[6 12 12 18 27],我希望 shortestPathSLice 作为 [[0 6 0 0 0]] 对于第二次迭代,我的 LowEstimate 数组是:[35 37 38 39],我希望 shortestPathSLice 为 [[0 6 35 0 0]]
-
好的,这意味着你应该在你的内部循环中使用
shortestPathSLice[0][index] = lowEstimate[0]。 -
看看this 初始化二维切片的页面