问题
Is there a difference between Array
and Vector
?
typeof(Array([1,2,3]))
Vector{Int64}
typeof(Vector([1,2,3]))
Vector{Int64}
Both seem to create the same thing, but they are not the same:
Array == Vector
false
Array === Vector
false
So, what is actually the difference?
回答1:
The difference is that Vector
is a 1-dimensional Array
, so when you write e.g. Vector{Int}
it is a shorthand to Array{Int, 1}
:
julia> Vector{Int}
Array{Int64,1}
When you call constructors Array([1,2,3])
and Vector([1,2,3])
they internally get translated to the same call Array{Int,1}([1,2,3])
as you passed a vector to them.
You would see the difference if you wanted to pass an array that is not 1-dimensional:
julia> Array(ones(2,2))
2×2 Array{Float64,2}:
1.0 1.0
1.0 1.0
julia> Vector(ones(2,2))
ERROR: MethodError: no method matching Array{T,1} where T(::Array{Float64,2})
Also note the effect of:
julia> x=[1,2,3]
3-element Array{Int64,1}:
1
2
3
julia> Vector(x)
3-element Array{Int64,1}:
1
2
3
julia> Vector(x) === x
false
So essentially the call Vector(x)
makes a copy of x
. Usually in the code you would probably simply write copy(x)
.
A general rule is that Array
is a parametric type that has two parameters given in curly braces:
- the first one is element type (you can access it using
eltype
) - the second one is the dimension of the array (you can access it using
ndims
)
See https://docs.julialang.org/en/v1/manual/arrays/ for details.
回答2:
Vector
is an alias for a one-dimensional Array
. You can see that in the Julia REPL:
julia> Vector
Array{T, 1} where T
julia> Vector{Int32}
Array{Int32, 1}
Similarly, a Matrix
is a 2-dimensional Array:
julia> Matrix
Array{T,2} where T
来源:https://stackoverflow.com/questions/61171531/difference-between-array-and-vector