在朱

2017-08-16 61 views
0

在該推壓到載體的載體是使用朱莉婭0.6在朱

說我有整數

x = Vector{Int64}[] resize!(x, 10) fill!(x, [0])

我要推到所選擇的載體外載體內的向量的向量,但不能讓它工作。

push!(x[1], 2) 

julia> x 
10-element Array{Array{Int64,1},1}: 
[0, 2] 
[0, 2] 
[0, 2] 
[0, 2] 
[0, 2] 
[0, 2] 
[0, 2] 
[0, 2] 
[0, 2] 
[0, 2] 

它最終將對推向每個向量。我在想這個錯誤的方式嗎?有沒有辦法只推送一個選定的矢量?

使用某個矢量的視圖並沒有幫助。

a = x[1] 
push!(a, 3) 

julia> x 
10-element Array{Array{Int64,1},1}: 
[0, 2, 3] 
[0, 2, 3] 
[0, 2, 3] 
[0, 2, 3] 
[0, 2, 3] 
[0, 2, 3] 
[0, 2, 3] 
[0, 2, 3] 
[0, 2, 3] 
[0, 2, 3] 

可以做到這一點嗎?

+5

的問題是'fill'。通過'fill!(x,[0])'將數組初始化爲'x = [[0] for i = 1:10]' –

+2

,'x'的每個元素都綁定到完全相同的矢量'[0] ':'x [1] === x [2]#=> true',所以如果你改變'[0]',所有相應綁定的內容都會改變。 – Gnimuc

+0

這是一個錯誤?爲什麼填充不能複製? –

回答

-1

`deepcopy'應該有助於獲得單獨的對象/數組。然而,令人驚訝的是它不起作用?!

julia> x = Vector{Int64}[]; 
julia> resize!(x, 10); 
julia> fill!(x, [0]) 
10-element Array{Array{Int64,1},1}: 
[0] 
[0] 
[0] 
[0] 
[0] 
[0] 
[0] 
[0] 
[0] 
[0] 

julia> x = deepcopy(x) 
julia> push!(x[1], 2) 
    10-element Array{Array{Int64,1},1}: 
[0, 2] 
[0, 2] 
[0, 2] 
[0, 2] 
[0, 2] 
[0, 2] 
[0, 2] 
[0, 2] 
[0, 2] 
[0, 2] 

並非是我期待