我正在将一个程序从 C 移植到 TCL,我正在尝试在 C 中实现类似于数组的数据结构。我需要它做的两件主要事情是
- 被订购
- 允许插入任何索引
- 从过程中返回数组
我会在运行时之前知道数组的大小,并且在整个程序中大小不应该改变(所以它是静态的)。是否有符合此要求的数据结构?
如果重要的话,我正在使用 TCL 8.6
编辑:我还需要能够从函数返回数据结构。
最佳答案
对应的数据结构是list
。它满足您的所有要求。如果您希望它具有固定大小,您可以像这样“预分配”它:
set data [lrepeat 8 {}]
这会创建八个空隔间。
它是有序的,您可以通过索引(从 0 开始)访问每个元素,并且可以将其值传递给过程/函数并返回它。您可以使用例如遍历它foreach
和for
,还有很多列表操作命令。
虽然
list
是最接近 C 数组的 Tcl 数据容器,但可以使用 array
或 dict
来模拟一个固定大小的,直接访问,有序容器。
# allocation
set listdata [lrepeat 8 {}]
array set arraydata {0 {} 1 {} 2 {} 3 {} 4 {} 5 {} 6 {} 7 {}}
set dictdata [dict create 0 {} 1 {} 2 {} 3 {} 4 {} 5 {} 6 {} 7 {}]
# or
set dictdata {0 {} 1 {} 2 {} 3 {} 4 {} 5 {} 6 {} 7 {}}
# access (write, then read)
lset listdata 5 96
lindex $listdata 5 ;# -> 96
set arraydata(5) 96
set arraydata(5) ;# -> 96
dict set dictdata 5 96
dict get $dictdata 5 ;# -> 96
# return from procedure
# (not possible with arraydata, arrays are shared using either
# scope manipulation or namespaces)
return $listdata
return $dictdata
# traversal
for {set i 0} {$i < 8} {incr i} {puts [lindex $listdata $i]}
# or
foreach elem $listdata {puts $elem}
for {set i 0} {$i < 8} {incr i} {puts [lindex $arraydata($i)]}
dict for {idx val} $dictdata {puts $val}
文档:array , dict , for , foreach , incr , lindex , lrepeat , lset , puts , return , set
关于TCL 中的类 C 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31568245/