记录 JuAFEM 2 -- `Base.ht_keyindex2!` 与 `Base._setindex!`

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 就是用来取对应键的引索值,找不到就返回 -1ht_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.valsh.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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值