版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mifangdebaise/article/details/82933733
JuAFEM 中 Base.ht_keyindex2!
与 Base._setindex!
Base.ht_keyindex2!
与 setindex!(Base._setindex!)
出现在 DofHander.jl
中,两个函数配合使用,在 Julia中文论坛 的一个提问 Base.ht_keyindex2! 函数的用法 中给出了 Base.ht_keyindex
的解释,抄过来如下
julia 哈希表的键值对分别存在两个
Array
里,所以会有相应的引索,ht_keyindex
就是用来取对应键的引索值,找不到就返回-1
。ht_keyindex2!
也差不多,只是在取不存在的键时,会返回那个键应在位置引索值的相反数 (真绕口,不如看源码 )
julia> h = Dict("A"=>1, "B"=>2)
Dict{String,Int64} with 2 entries:
"B" => 2
"A" => 1
julia> h.keys # 存放键的数组
16-element Array{String,1}:
#undef
"B"
"A"
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
julia> h.vals # 存放值的数组
16-element Array{Int64,1}:
244450080
2
1
244449856
244449856
244449856
244449856
244452208
244452208
244449856
244449856
244449856
244514840
244514840
244449856
257113136
julia> Base.ht_keyindex(h, "B") # 取 “B” 这个键在数组中的位置
2
julia> h.keys[2] # 验证一下
"B"
julia> Base.ht_keyindex(h, "C") # 不存在的键返回 -1
-1
ht_keyindex2!
接以上代码
1 看上去直接给h.vals
与h.keys
赋值并不能新增键值对。
2 键不存在时,ht_keyindex2!
返回的值会告诉你,插入对应的键会放在哪。(其实这里颠倒了因果,因为插入的位置就是根据ht_keyindex2!
的返回值确定的,ref:julia/dict.jl at master · JuliaLang/julia)
julia> h.keys[4] = "C"
"C"
julia> h
Dict{String,Int64} with 2 entries:
"B" => 2
"A" => 1
julia> h.vals[4] = 3
3
julia> h
Dict{String,Int64} with 2 entries:
"B" => 2
"A" => 1
julia> h.vals
16-element Array{Int64,1}:
244450080
2
1
3
244449856
244449856
244449856
244452208
244452208
244449856
244449856
244449856
244514840
244514840
244449856
257113136
julia> h.keys
16-element Array{String,1}:
#undef
"B"
"A"
"C"
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
julia> Base.ht_keyindex2!(h, "C") # 如果有键 “C”,应该放在第 6 位
-6
julia> setindex!(h, 3, "C") # 插入键值对
Dict{String,Int64} with 3 entries:
"B" => 2
"A" => 1
"C" => 3
julia> h.keys # 检查效果
16-element Array{String,1}:
#undef
"B"
"A"
"C"
#undef
"C"
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
注意上面的代码用的是 setindex!
,我们可以自己调用 Base._setindex!
来手动添加 "C"
到相应的位置,例如下面我们将 "D"
添加到 h
的相应索引位置
julia> token = Base.ht_keyindex2!(h, "D") # 如果有键 “D”,应该放在第 11 位
-11
julia> valueD = 4
4
julia> Base._setindex!(h, valueD, "D", -token) # 调用 Base._setindex!,手动将位置输入
julia> h
Dict{String,Int64} with 4 entries:
"B" => 2
"A" => 1
"C" => 3
"D" => 4
julia> h.keys
16-element Array{String,1}:
#undef
"B"
"A"
"C"
#undef
"C"
#undef
#undef
#undef
#undef
"D"
#undef
#undef
#undef
#undef
#undef