从索引数组中提取索引:保证要排序? [英] Extracting indices from indexed array: guaranteed to be ordered?

查看:48
本文介绍了从索引数组中提取索引:保证要排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道对于 associative 数组,数组键没有固有的顺序:

I know that for associative arrays, there's no inherent order for the array keys:

declare -A map=([a]=b [c]=d [e]=f)
echo "${!map[@]}"   # => e c a (perhaps)

那索引数组呢?

尝试一下:

declare -a list
for i in {1..1000}; do list[RANDOM]=1; done
echo "${!list[@]}"

看来索引是按数字顺序排列的.但是我可以依靠吗?

It appears that the indices are numerically ordered. But can I rely on that?

推荐答案

我花了一些时间阅读 bash来源.索引数组被实现为双链表.

I spent some time reading the bash source. Indexed arrays are implemented as doubly-linked lists.

插入新的数组元素( ary [i] = value )将遍历列表并插入元素,以使索引保持数字排序:

Inserting new array elements (ary[i]=value) will walk the list and insert the element such that the indices remain numerically sorted: https://git.savannah.gnu.org/cgit/bash.git/tree/array.c#n548

提取索引( $ {!ary [@]} )将列表从头(具有最大索引的元素)移至尾部(最小索引),并建立一个列表索引: https://git.savannah.gnu.org/cgit/bash.git/tree/array.c#n778

Extracting the indices (${!ary[@]}) walks the list from the head (the element with the max index) back to the tail (min index) and build a list of indices: https://git.savannah.gnu.org/cgit/bash.git/tree/array.c#n778

因此,目前已实施,我想我可以确信索引列表的确是有序的.

So, as currently implemented, I think I can feel confident that the list of indices is indeed ordered.

这篇关于从索引数组中提取索引:保证要排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆