user2820579
user2820579

Reputation: 3451

Initialize array of arrays for construction on the fly

How do you declare an array that contain arrays in julia?

I have a=Int32[] which creates an empty array of Int32 (of course), but I would like later to construct on the fly something like

if ...
    push!(a, [r,s]) # (*)
...

where r and s are integers. I tried a=Int32[Int32[]] but it does not work when doing (*). I don't have the specific shape of a, so I need to declare it without this restriction.

Upvotes: 1

Views: 127

Answers (1)

gggg
gggg

Reputation: 2386

Int32[] creates a Vector{Int32} which is a Vector with element type Int32. You want a Vector with element type Vector{Int32}, so you can use Vector{Vector{Int32}}() or Vector{Int32}[]. Note that Vector{T} is an alias for Array{T,1}, aka an Array with element type T and 1 dimension, so when Julia prints out the type, it won't use the word Vector.

julia> v=Vector{Vector{Int32}}()
0-element Array{Array{Int32,1},1}

julia> push!(v,[1,2,3])
1-element Array{Array{Int32,1},1}:
 Int32[1, 2, 3]

or

julia> x=Vector{Int32}[]
0-element Array{Array{Int32,1},1}

julia> push!(x,[4,5,6])
1-element Array{Array{Int32,1},1}:
 Int32[4, 5, 6]

Upvotes: 9

Related Questions