TCL中的C-Like数组

wat*_*ake 2 c arrays tcl data-structures

我正在将程序从C移植到TCL,我正在尝试实现类似于C中的数组的数据结构.我需要做的两件事是

  • 被订购
  • 允许插入任何索引
  • 从过程返回数组

我会在运行时知道数组的大小,并且整个程序的大小不应该改变(所以它是静态的).是否有适合此法案的数据结构?

如果重要,我正在使用TCL 8.6

编辑:我还需要能够从函数返回数据结构.

Pet*_*rin 5

相应的数据结构将是list.它符合您的所有要求.如果你想让它有一个固定的大小,你就像这样"预先分配"它:

set data [lrepeat 8 {}]
Run Code Online (Sandbox Code Playgroud)

这会产生八个空的隔间.

它是有序的,您可以通过索引(从0开始)访问每个元素,并且您可以将其值传递给过程/函数并返回它.您可以使用eg foreach和遍历它for,并且有很多列表操作命令.


虽然listTcl数据容器最接近C数组,但可以使用arraydict模拟固定大小,直接访问的有序容器.

# 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}
Run Code Online (Sandbox Code Playgroud)

文档:array,dict,for,foreach,incr,lindex,lrepeat,lset,puts,return,set