TCL 中的类 C 数组

标签 c arrays data-structures tcl

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

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

我会在运行时之前知道数组的大小,并且在整个程序中大小不应该改变(所以它是静态的)。是否有符合此要求的数据结构?

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

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

最佳答案

对应的数据结构是list。它满足您的所有要求。如果您希望它具有固定大小,您可以像这样“预分配”它:

set data [lrepeat 8 {}]

这会创建八个空隔间。

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


虽然 list 是最接近 C 数组的 Tcl 数据容器,但可以使用 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}

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

关于TCL 中的类 C 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31568245/

相关文章:

c - C 中 malloc() 触发断点

java - 关于选择算法

algorithm - 并发重读工作负载的数据结构

c++ - 最适合拼写检查器、词典和词库的算法和数据结构

c - 简单程序中的 <Error> <main.c>

C - 段错误和 strlen

c - 在 gdb 调试器中找不到调试符号

c - 在 gcc 4.2.1 上,指向二维数组的指针的大小为 8 的原因是什么?

c - 查找数组中重复的整数

javascript - 使用 AJAX 将 JavaScript 数组传递给cherrypy