为什么这两种构造数组的不同方式会产生不同的行为? [英] Why do these two different ways of constructing an array produce different behaviors?

查看:61
本文介绍了为什么这两种构造数组的不同方式会产生不同的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我以两种不同的方式(例如ab)构造2元素数组时,将元素添加到内部数组之一中时会得到两个不同的结果.append!也会发生这种情况.构建每个对象后的输出,我希望它们是完全相同的吗?

When I construct a 2 element array in two different ways(e.g. a and b, I get two different results when I add an element to one of the inner arrays. This also happens with append!. Based on the output after constructing each, I'd expect them to be exactly the same?

julia> a = [[],[]]
2-element Array{Array{Any,1},1}:
 Any[]
 Any[]

julia> push!(a[1],1.0)
1-element Array{Any,1}:
 1.0

julia> a
2-element Array{Array{Any,1},1}:
 Any[1.0]
 Any[]

julia> b = fill([],2)
2-element Array{Array{Any,1},1}:
 Any[]
 Any[]

julia> push!(b[1],1.0)
1-element Array{Any,1}:
 1.0

julia> b
2-element Array{Array{Any,1},1}:
 Any[1.0]
 Any[1.0]

推荐答案

fill将创建一个数组,该数组初始化为 same 对象的n个副本(浅),因此b[1] == = b[2],并且在更新b[1]时,您将更新在b[2]中也指向的同一对象.

fill will create an array initialized with n copies (shallow) of the same object, so that b[1] === b[2], and when you update b[1], you're updating the same object that's also pointed to in b[2].

这篇关于为什么这两种构造数组的不同方式会产生不同的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆