Create vectors of new types in Julia

Asked

Viewed 147 times

4

I can’t create vectors of new types in Juulia, they don’t work.

The example program is this:

# Meu tipo customizado
struct Job
    id::Int64
    order::Int64
    time::Float64
end

#Aqui eu crio o vetor
v = Vector{Job}()

#crio jobs para inserir no vetor
j1 = Job(1,1,1.0)
j2 = Job(2,1,1.1)
j3 = Job(3,1,1.2)

#As linhas seguintes não funcionam
append!(v, j1)
append!(v, j2)
append!(v, j3)


v #Vetor ainda vazio

I tested the same logic with integers in place of Jobs and it just worked.

1 answer

4


To insert an element of type struct in the vector, you must use the macro push!:

push!(v, j1)
push!(v, j2)
push!(v, j3)

Or, if you prefer to insert the three items in a single command:

push!(v, j1, j2, j3)

Upshot:

julia> v
3-element Array{Job,1}:
 Job(1, 1, 1.0)
 Job(2, 1, 1.1)
 Job(3, 1, 1.2)

The macro append! is used to insert a array of elements:

append!(v, [j1, j2, j3])

Result (after inserting the three elements again):

julia> v
6-element Array{Job,1}:
 Job(1, 1, 1.0)
 Job(2, 1, 1.1)
 Job(3, 1, 1.2)
 Job(1, 1, 1.0)
 Job(2, 1, 1.1)
 Job(3, 1, 1.2)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.