我正在尝试运行2 for循环以访问数组中的2个元素(例如)
x = 100
for i in eachindex(x-1)
for j in 2:x
doSomething = Array[i] + Array[j]
end
end
而且(经常(并非总是))出现此错误或类似错误:
LoadError: BoundsError: attempt to access 36-element Array{Any,1} at index [64]
我知道有运行这些循环的正确方法,以避免边界错误,因此我使用eachindex(x-1) == 1:x
,对于2:x
,我将如何处理?
我对Julia来说还比较陌生,如果这不是边界错误的原因,那会是什么?-谢谢
编辑:我要运行的简化版本(也是,矢量数组)
all_people = Vector{type_person}() # 1D Vector of type person
size = length(all_people)
... fill vector array to create an initial population of people ...
# Now add to the array using existing parent objects
for i in 1:size-1
for j in 2:size
if all_people[i].age >= all_people[j].age # oldest parent object forms child variable
child = type_person(all_people[i])
else
child = type_person(all_people[j])
end
push!(all_people, child) # add to the group of people
end
end
我很少猜测,但是也许这是您想要的代码:
struct Person
parent::Union{Nothing,Person}
age::Int
end
Person(parent::Person) = Person(parent,0)
N = 100
population = Person.(nothing, rand(20:50,N))
for i in 1:(N-1)
for j in (i+1):N
parent = population[population[i].age >= population[j].age ? i : j]
push!(population, Person(parent))
end
end
注意:
Parameters.jl
包-对于代理构造函数来说非常方便Person
)eachindex
应在Array
s上使用-在标量上没有意义