选择集合时先列出操作:怎样查找、在哪一端增删、是否要求顺序、是否需要范围扫描,以及键值大小与数量分布。单独比较一个 O(1) 与 O(log n),会漏掉哈希、字符串比较、分配和缓存访问的成本。
按操作速查
以下复杂度把一次键比较或哈希的成本单独留给具体类型;摊销不表示每一次操作都同样快。
结构 强项 代价或条件
Vec 连续遍历、O(1) 索引、摊销 O(1) 尾部 push 中间插删通常移动 O(n) 元素
VecDeque 两端增删、FIFO、O(1) 索引 环形布局可能分成两个切片
HashMap<K,V> 期望快速按键查找与更新 无排序保证;成本受哈希与分布影响
BTreeMap<K,V> 有序遍历、范围与最邻近查询 查找/更新通常 O(log n) 次结构操作
BinaryHeap 查看最大项 O(1),优先队列 不提供整体有序迭代;pop 通常 O(log n)
排序 Vec 批量构建、频繁读取与二分查找 维持有序的插入通常 O(n)
HashSet/BTreeSet 对应只存键的需求;固定数量可使用数组。是否使用内联小容器,应依据实际容量分布与所选库规则,不存在通用“少于 20 项就零堆分配”的阈值。标准库集合概览
Vec:容量不是长度
0 有效元素 1 有效元素 2 有效元素 3 空余容量 4 空余容量 5 空余容量 len = 3 capacity ≥ 6 Vec:已初始化长度与可用容量不同 示意非零大小 T;只有前 len 项是可作为 T 读取和析构的已初始化元素。
Vec 包含指针、长度和容量信息,但字段顺序不作为稳定 C 布局承诺。它自身可以在栈上、堆上或其他对象内部,不能一概称为“栈上的 24 字节”。零大小元素与零容量还具有特殊分配行为。
with_capacity(n) 请求至少 n 项容量,不创建 n 个已初始化 T。reserve(additional) 按当前长度加 additional 计算需求,不是直接设置最终容量。普通 push 在容量足够时无需扩容;扩容策略与增长倍数不是应用可依赖的永久公式。Vec 保证
fn main ( ) {
let mut values = Vec :: with_capacity( 8 ) ;
assert_eq! ( values.len ( ) , 0 ) ;
assert! ( values.capacity ( ) > = 8 ) ;
values.extend ( [ 10 , 20 , 30 ] ) ;
values.clear ( ) ;
assert! ( values.is_empty ( ) ) ;
assert! ( values.capacity ( ) > = 8 ) ; }
可能扩容的操作使缓存裸指针失去有效性,安全借用规则会限制冲突访问。即使没扩容,insert、remove、sort 等也可能改变索引对应的对象;“地址没变”和“仍是原先那个逻辑元素”不是同一件事。
swap_remove 可用末项替换被删位置,避免保持顺序所需的移动,代价是顺序改变。需要长期稳定标识时,应设计 ID、代际索引或合适的间接存储,不要把当前下标当作永久身份。
删除时把顺序与身份分开
fn main ( ) {
let original = vec! [ ( 10 , " a" ) , ( 20 , " b" ) , ( 30 , " c" ) , ( 40 , " d" ) ] ;
let mut ordered = original.clone ( ) ;
assert_eq! ( ordered.remove ( 1 ) , ( 20 , " b" ) ) ;
assert_eq! ( ordered, [ ( 10 , " a" ) , ( 30 , " c" ) , ( 40 , " d" ) ] ) ;
let mut unordered = original;
assert_eq! ( unordered.swap_remove ( 1 ) , ( 20 , " b" ) ) ;
assert_eq! ( unordered, [ ( 10 , " a" ) , ( 40 , " d" ) , ( 30 , " c" ) ] ) ;
assert_eq! ( unordered[ 1 ] .0 , 40 ) ; }
若另有 HashMap<ID, usize> 维护位置,swap_remove 后必须更新被搬来末项的索引,否则查询会定位到错误对象。ID 解决逻辑身份,映射维护解决存储位置,两者缺一不可。单纯将 Vec 元素改成 Box 只能让未移动的堆对象地址更稳定,不能防止对象被删除或旧 ID 被复用。
HashMap:哈希、相等与随机种子共同构成契约
相等的键必须产生相等的哈希结果。自定义 Hash 与 Eq 需要相互一致;键放入后不能通过内部可变性等方式改变参与哈希或相等比较的部分,否则破坏集合约定。
标准库当前实现源于 SwissTable,并使用带随机状态的默认哈希构造器;默认算法与细节可演进。随机状态并非简单的“每次进程启动只有一个所有表共享的固定种子”。选择替代哈希器时应结合输入威胁模型、键长度和测量,不承诺固定快 10% 或 30%。HashMap
Entry 接口把查询与插入意图放在一次操作中:
use std:: collections:: HashMap;
fn main ( ) {
let mut counts = HashMap:: new( ) ;
for word in [ " red" , " blue" , " red" ] {
* counts.entry ( word) .or_insert ( 0_ u32 ) + = 1 ;
}
assert_eq! ( counts.get ( " red" ) , Some ( & 2 ) ) ;
}
不要依赖 HashMap 遍历顺序生成稳定快照或测试期望。当前实现遍历可能按 capacity 而不是仅按 len 扫描,曾经很大而后来变稀疏的表值得单独测量。需要稳定顺序时,显式排序输出或选择有序结构。
借用查询避免为了查找而分配
use std:: collections:: HashMap;
fn main ( ) {
let mut values: HashMap< String, Vec< u32 > > = HashMap:: new( ) ;
values.insert ( String :: from( " red" ) , vec! [ 1 ] ) ;
assert_eq! ( values.get ( " red" ) .map ( Vec :: len) , Some ( 1 ) ) ;
let mut constructed = 0 ;
values.entry ( String :: from( " red" ) ) .or_insert_with ( | | {
constructed + = 1 ;
vec! [ 99 ]
} ) .push ( 2 ) ;
assert_eq! ( constructed, 0 ) ;
assert_eq! ( values.get ( " red" ) .unwrap ( ) , & [ 1 , 2 ] ) ;
}
String 键可以借用 str 查询,因为相应 Borrow 契约使两种表示的相等与哈希一致。这个能力并不意味着任意自定义“可转成字符串”的类型都适合 Borrow:若键按忽略大小写比较,而普通 str 按大小写敏感比较,两者就不具有同一种键语义。
or_insert_with 只在空缺时构造值,但本例传给 entry 的 String 仍在调用前创建。热点若主要是命中,可以衡量先 get_mut、缺失再创建键的路径;它减少命中时的键分配,却可能使缺失路径多一次查找。不要把 Entry 理解成键和值都自动惰性创建。HashMap 借用查询
BTreeMap:顺序是接口能力,不是性能附赠
BTreeMap 依据 Ord 排序,适合范围查询、寻找边界和有序输出。节点内部存放多项,具有一定局部性,但整个树不是一个连续数组。排序 Vec 也能同时提供连续布局与有序读取,所以“缓存局部性和顺序不能兼得”并不成立。
use std:: collections:: BTreeMap;
fn main ( ) {
let values = BTreeMap:: from( [ ( 10 , " a" ) , ( 20 , " b" ) , ( 30 , " c" ) ] ) ;
let selected: Vec< _ > = values.range ( 15 .. = 30 )
.map ( | ( &key , &value ) | ( key, value) ) .collect ( ) ;
assert_eq! ( selected, [ ( 20 , " b" ) , ( 30 , " c" ) ] ) ;
}
选择树还是排序 Vec,要比较更新频率与范围读取:一批数据构建后长期只读,排序 Vec 往往值得测;频繁在线插删则可能更适合树。键比较若涉及长字符串,比较本身的成本也应算入。
最近边界查询需要明确包含关系
use std:: collections:: BTreeMap;
fn main ( ) {
let changes = BTreeMap:: from( [ ( 10 , " v1" ) , ( 20 , " v2" ) , ( 30 , " v3" ) ] ) ;
let at = | time | changes.range ( .. = time) .next_back ( ) .map ( | ( _, v ) | * v) ;
assert_eq! ( at ( 9 ) , None ) ;
assert_eq! ( at ( 20 ) , Some ( " v2" ) ) ;
assert_eq! ( at ( 25 ) , Some ( " v2" ) ) ;
let sorted = [ ( 10 , " v1" ) , ( 20 , " v2" ) , ( 30 , " v3" ) ] ;
let end = sorted.partition_point ( | ( time , _) | * time < = 25 ) ;
let predecessor = end.checked_sub ( 1 ) .map ( | i | sorted[ i] .1 ) ;
assert_eq! ( predecessor, Some ( " v2" ) ) ;
}
这里查询的是“不晚于 time 的最后一次变化”。树用有序 range 再 next_back,排序切片用 partition_point 找到第一个大于 time 的位置。切片在最早时间之前会返回 0,因此需要 checked_sub 处理不存在前驱。若允许相同时间重复,Map 的同键插入会替换值,Vec 则可保留多项,必须另定并列事件顺序。BTreeMap 范围
VecDeque:逻辑连续不等于物理连续
环形缓冲允许前端和尾端高效操作,扩容仍可能发生。as_slices 返回两段,按顺序连接才是逻辑内容;make_contiguous 可整理成一个连续切片,但整理本身可能需要移动元素。VecDeque
use std:: collections:: VecDeque;
fn main ( ) {
let mut queue = VecDeque:: from( [ 1 , 2 , 3 ] ) ;
assert_eq! ( queue.pop_front ( ) , Some ( 1 ) ) ;
queue.push_back ( 4 ) ;
let ( a, b) = queue.as_slices ( ) ;
let logical: Vec< _ > = a.iter ( ) .chain ( b) .copied ( ) .collect ( ) ;
assert_eq! ( logical, [ 2 , 3 , 4 ] ) ;
}
不要为了把 Vec 当 FIFO 而不断 remove(0):每次都移动剩余元素,长队列会积累大量工作。若业务只需批量读取然后整体清空,Vec 仍可能合适,操作模式比容器名字更重要。
逻辑队列怎样跨过物理末端?
把 A、B、C 看作逻辑身份,把格子编号看作物理位置。头部接近缓冲末端时,队列仍按 A、B、C 排列,只是存储分成两段。公式中的取模解释了这种折返;它不表示 Rust 的索引会允许任意越界值。
p ( i ) = ( h + i ) mod C , 0 ≤ i < len ≤ C
正在呈现知识画面 重新加载
逻辑队列怎样跨过物理末端? 环形缓冲的逻辑下标映射到 (head+i) mod capacity;两段拼接保留队列顺序。
{"id":"rust-vecdeque-wrap","title":"逻辑队列怎样跨过物理末端?","summary":"环形缓冲的逻辑下标映射到 (head+i) mod capacity;两段拼接保留队列顺序。","height":1000,"html":"<h2 data-i18n=\"heading\"></h2><p class=\"intro\" data-i18n=\"intro\"></p><div class=\"control\"><label for=\"head\" data-i18n=\"head\"></label><output for=\"head\" id=\"head-value\"></output><input id=\"head\" type=\"range\" min=\"0\" max=\"7\" value=\"6\" step=\"1\"></div><div class=\"control\"><label for=\"length\" data-i18n=\"length\"></label><output for=\"length\" id=\"length-value\"></output><input id=\"length\" type=\"range\" min=\"0\" max=\"8\" value=\"5\" step=\"1\"></div><div class=\"track-row\"><span data-i18n=\"physical\"></span><div id=\"physical\" class=\"track\"></div></div><section class=\"panel\"><h3 data-i18n=\"first\"></h3><div id=\"first\"></div></section><section class=\"panel\"><h3 data-i18n=\"second\"></h3><div id=\"second\"></div></section><section class=\"panel\"><h3 data-i18n=\"logical\"></h3><div id=\"logical\"></div></section><div class=\"copy\"><p id=\"explanation\" role=\"status\"></p><p class=\"reserve\" aria-hidden=\"true\" data-i18n=\"explain\"></p></div><details class=\"scope\"><summary data-i18n=\"scopeLabel\"></summary><p data-i18n=\"scope\"></p></details>","css":".intro{margin:8px 0 18px;color:var(--muted);font-size:14px}.caption,.hint{font-size:12px;color:var(--muted);margin-top:12px}.control{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:6px 12px;align-items:center;margin:14px 0;font-size:13px}.control label{font-size:13px}.control output{color:var(--accent);min-width:5em;text-align:right;font-variant-numeric:tabular-nums}.control input{grid-column:1/-1;width:100%;margin:0}.presets{display:flex;gap:4px;align-items:stretch}.presets button{flex:1 1 0;min-width:0;overflow-wrap:anywhere;font-size:13px}.actions{display:flex;gap:8px;flex-wrap:wrap;margin:14px 0}.actions button{flex:1;min-width:0;font-size:13px;min-height:42px}.copy{display:grid;font-size:14px;margin:16px 0}.copy>*{grid-area:1/1;margin:0}.reserve{visibility:hidden}.scope{margin-top:14px;color:var(--muted);font-size:12px}.scope summary{padding:8px 0;cursor:pointer}.scope p{margin-top:10px}.two{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin:16px 0}.card{border:1px solid var(--rule);border-radius:9px;padding:14px;min-width:0}.card header{font-size:14px;font-weight:600;margin-bottom:10px}.card button{font-size:12px;width:100%;min-width:0}.card small{display:block;font-size:12px;color:var(--muted)}.card code{font-size:12px;overflow-wrap:anywhere}.metrics{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin:16px 0}.metrics>div{border-left:2px solid var(--accent);padding-left:10px;min-width:0}.metrics span{display:block;min-height:3.2em;color:var(--muted);font-size:12px}.metrics strong{font-size:23px;display:block;font-weight:550;overflow-wrap:anywhere;font-variant-numeric:tabular-nums}.formula{border-top:1px solid var(--rule);padding-top:12px;margin-top:14px;font-size:13px;font-variant-numeric:tabular-nums;overflow-wrap:anywhere}.value{font:550 20px ui-monospace,monospace}.legend{display:flex;flex-wrap:wrap;gap:6px 14px;font-size:12px;color:var(--muted);margin:12px 0}.legend span:before{content:'';display:inline-block;width:8px;height:8px;border-radius:2px;background:var(--accent);margin-right:6px}.legend .second:before{background:var(--second)}.check{display:flex;align-items:center;gap:8px;font-size:13px;margin:12px 0}.check input{width:16px;height:16px;flex-shrink:0;accent-color:var(--accent)}select,input[type=text],input[type=number]{background:var(--paper);color:var(--ink);font:inherit;font-size:13px;padding:10px;border:1px solid var(--rule);border-radius:7px;max-width:100%;min-width:0}select{width:100%;min-height:42px}.band{height:20px;display:flex;background:var(--surface);border-radius:4px;overflow:hidden}.band i{height:100%;display:block;background:var(--accent);transition:width .25s}.band i.second{background:var(--second)}button:disabled{cursor:default}.status{font-size:13px;min-height:4.8em}.mono{font-family:ui-monospace,monospace;font-variant-numeric:tabular-nums}.muted{color:var(--muted)}\n@media(max-width:480px){.two{gap:8px}.card{padding:12px 9px}.actions button,.presets button{font-size:12px}.metrics strong{font-size:20px}.metrics{gap:8px}}\n@media(prefers-reduced-motion:reduce){*,*::before,*::after{transition:none!important;animation:none!important}}\n.track-row{margin:16px 0}.track-row>span{display:block;font-size:12px;color:var(--muted);margin-bottom:7px}.track{display:flex;gap:5px;min-width:0}.cell{flex:1;min-width:0;min-height:48px;border:1px solid var(--rule);border-radius:5px;background:var(--surface);display:flex;align-items:center;justify-content:center;text-align:center;padding:5px 3px;font-size:12px;overflow-wrap:anywhere;font-variant-numeric:tabular-nums}.cell.on{background:var(--accent-soft);border-color:var(--accent)}.cell.gold{background:var(--second-soft);border-color:var(--second)}.cell.empty{border-style:dashed;color:var(--muted)}.cell.error{border-color:var(--second);text-decoration:line-through}.choices{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px;margin:14px 0}.choices button{min-width:0;padding:10px 4px;font-size:12px;overflow-wrap:anywhere}.choices button[aria-current=true]{border-color:var(--accent);background:var(--accent-soft)}.relation{display:grid;grid-template-columns:minmax(0,1fr) 28px minmax(0,1fr);align-items:center;gap:6px;margin:12px 0}.relation .cell{min-height:72px}.relation>i{text-align:center;font-style:normal;color:var(--accent)}.readout{font-size:13px;white-space:pre-line;min-height:6.4em;overflow-wrap:anywhere}.plot{position:relative;border-left:1px solid var(--rule);border-bottom:1px solid var(--rule);padding:8px 0;margin:18px 0}.plot-row{height:28px;position:relative;margin:4px 0;background:var(--surface)}.plot-row i{position:absolute;inset-block:5px;background:var(--accent);min-width:2px;transition:width .2s,left .2s}.plot-row b{position:relative;padding:4px 6px;font:11px/28px ui-monospace,monospace;background:var(--paper);border-radius:3px}.axis{display:flex;justify-content:space-between;font-size:11px;color:var(--muted)}\n\n/* Action labels must remain readable across locales and narrow embeds. */\n.actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}\n.actions button{overflow-wrap:anywhere;white-space:normal;min-height:58px;padding:8px}\nbutton{overflow-wrap:anywhere}\n@media(min-width:640px){.actions{grid-template-columns:repeat(3,minmax(0,1fr))}}\n\n.metrics span{overflow-wrap:anywhere}\n.panel{border:1px solid var(--rule);border-radius:9px;padding:12px;margin:14px 0;min-width:0}.panel h3{font-size:13px;margin:0 0 10px;color:var(--muted)}.source{font:13px/1.8 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere;margin:12px 0}.source mark{background:var(--accent-soft);color:var(--ink);border-bottom:2px solid var(--accent)}.source .fault{background:var(--second-soft);border-color:var(--second)}.diagram{display:block;width:100%;height:auto;max-height:320px;margin:14px 0;overflow:visible}.diagram text{fill:var(--ink);font:12px ui-monospace,monospace}.diagram .edge{stroke:var(--muted);stroke-width:1.5;fill:none}.diagram .edge.on{stroke:var(--accent);stroke-width:3}.diagram .node{fill:var(--surface);stroke:var(--rule);stroke-width:1.5}.diagram .node.on{fill:var(--accent-soft);stroke:var(--accent)}.diagram .node.gold{fill:var(--second-soft);stroke:var(--second)}.log{font:12px/1.8 ui-monospace,monospace;white-space:pre-line;overflow-wrap:anywhere;min-height:7.2em}.table{display:grid;gap:5px;margin:14px 0}.table .tr{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:5px}.table .tr>*{padding:8px 5px;background:var(--surface);border-radius:4px;min-width:0;overflow-wrap:anywhere;font-size:12px}.table .tr .on{background:var(--accent-soft)}.table .tr .gold{background:var(--second-soft)}.choices button{min-height:44px}.metrics strong{min-height:1.6em}.code-line{display:block}.code-line.on{background:var(--accent-soft);border-left:2px solid var(--accent);padding-left:6px}.status-badge{font-size:12px;color:var(--accent)}.tile-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px}.tile-grid .cell{min-height:40px}.actions button{min-height:48px}.form-field{display:grid;gap:8px;margin:14px 0;font-size:13px}.form-field input{width:100%;font-family:ui-monospace,monospace}.metrics.three{grid-template-columns:repeat(3,minmax(0,1fr))}.formula{min-height:3.2em}.presets{flex-wrap:wrap}.presets button{flex-basis:25%;min-height:44px}\n\n.budget{display:flex;height:28px;margin:16px 0;background:var(--surface);border-radius:5px;overflow:hidden}.budget i{display:block;background:var(--accent);transition:width .2s}.budget i.gold{background:var(--second)}.intervals{margin:16px 0}.interval{position:relative;height:36px;background:var(--surface);margin:6px 0;border-radius:4px;overflow:hidden}.interval i{position:absolute;height:100%;background:var(--accent-soft);border-left:2px solid var(--accent)}.interval i.gold{background:var(--second-soft);border-color:var(--second)}.interval span{position:relative;z-index:1;font:12px/36px ui-monospace,monospace;padding-left:7px}.table .tr>*{min-height:4.8em}.formula{white-space:pre-line;min-height:7.2em}.actions:has(>button:only-child){grid-template-columns:1fr}.metrics strong{min-height:3.2em}.rangegrid{display:grid;grid-template-columns:repeat(12,minmax(0,1fr));gap:3px;margin:14px 0}.rangegrid .cell{min-height:30px;padding:3px 1px;font-size:10px}.message{min-height:7.2em;white-space:pre-line;font:13px/1.8 ui-monospace,monospace;overflow-wrap:anywhere}\n/* Allow CJK hanging punctuation without overflowing a metric's border box. */\n.metrics>div{padding-right:4px}.metrics span{line-break:anywhere}\n\n.chart-wrap{margin:18px 0}.chart-label{font-size:12px;color:var(--muted);min-height:3.2em}.curve{display:block;width:100%;height:auto;max-height:320px;overflow:visible}.curve text{font:11px ui-monospace,monospace;fill:var(--muted)}.gridline{stroke:var(--rule);stroke-width:1}.metrics strong{font-size:20px;min-height:3.2em}.formula{font:12px/1.8 ui-monospace,monospace;min-height:9em}.readout{min-height:8em}.presets button{flex-basis:30%}.scope p{overflow-wrap:anywhere} .unit-note{font-size:12px;color:var(--muted);margin:10px 0}\n\n.metrics span{word-break:break-all;line-break:strict}.metrics>div{padding-right:6px}\n\n.cell{min-height:72px}.metrics strong{min-height:3.6em}\n\n.track{display:grid;grid-template-columns:repeat(4,minmax(0,1fr))}.panel>div{min-height:2.5em;font:14px/1.8 ui-monospace,monospace;overflow-wrap:anywhere}","js":"const $=s=>document.querySelector(s);const set=(id,v)=>$('#'+id).textContent=v;const t=k=>viz.t(k);function cells(id,values){$('#'+id).replaceChildren(...values.map(v=>{const e=document.createElement('div');e.className='cell '+(v.cls||'');e.textContent=v.text;e.title=v.title||v.text;return e;}));}function pressed(mode){document.querySelectorAll('[data-mode]').forEach(e=>e.setAttribute('aria-pressed',String(e.dataset.mode===mode)));}const esc=s=>String(s).replace(/[&<>\"']/g,c=>({'&':'&','<':'<','>':'>','\"':'"',\"'\":'''}[c]));const fmt=s=>'{'+[...s].sort().join(', ')+'}';function graph(id,nodes,edges){const el=$('#'+id);el.setAttribute('viewBox','0 0 360 200');el.innerHTML='<defs><marker id=\"arrow-'+id+'\" viewBox=\"0 0 10 10\" refX=\"8\" refY=\"5\" markerWidth=\"5\" markerHeight=\"5\" orient=\"auto-start-reverse\"><path d=\"M 0 0 L 10 5 L 0 10 z\" fill=\"var(--muted)\"/></marker></defs>'+edges.map(e=>{const a=nodes[e[0]],b=nodes[e[1]],dx=b.x-a.x,dy=b.y-a.y,d=Math.hypot(dx,dy)||1;if(edges.some(r=>r[0]===e[1]&&r[1]===e[0])){const nx=-dy/d,ny=dx/d;return '<path class=\"edge '+(e[2]?'on':'')+'\" d=\"M '+(a.x+dx/d*22+nx*12)+' '+(a.y+dy/d*22+ny*12)+' Q '+((a.x+b.x)/2+nx*38)+' '+((a.y+b.y)/2+ny*38)+' '+(b.x-dx/d*25+nx*12)+' '+(b.y-dy/d*25+ny*12)+'\" marker-end=\"url(#arrow-'+id+')\"/>';}return '<line class=\"edge '+(e[2]?'on':'')+'\" x1=\"'+(a.x+dx/d*25)+'\" y1=\"'+(a.y+dy/d*25)+'\" x2=\"'+(b.x-dx/d*28)+'\" y2=\"'+(b.y-dy/d*28)+'\" marker-end=\"url(#arrow-'+id+')\"/>';}).join('')+nodes.map(n=>'<g><circle class=\"node '+(n.cls||'')+'\" cx=\"'+n.x+'\" cy=\"'+n.y+'\" r=\"25\"/><text x=\"'+n.x+'\" y=\"'+(n.y+4)+'\" text-anchor=\"middle\">'+esc(n.name)+'</text>'+(n.sub?'<text x=\"'+n.x+'\" y=\"'+(n.y+43)+'\" text-anchor=\"middle\">'+esc(n.sub)+'</text>':'')+'</g>').join('');}function table(id,rows){$('#'+id).classList.add('table');$('#'+id).replaceChildren(...rows.map(r=>{const row=document.createElement('div');row.className='tr';row.style.gridTemplateColumns='repeat('+r.length+',minmax(0,1fr))';r.forEach(x=>{const c=document.createElement('div');if(typeof x==='object'){c.textContent=x.text;c.className=x.cls||'';}else c.textContent=x;row.append(c)});return row;}));}function band(id,parts,total){$('#'+id).replaceChildren(...parts.map((p,i)=>{const e=document.createElement('i');e.style.width=(100*p.value/total)+'%';e.className=i%2?'gold':'on';e.title=p.name+': '+p.value;return e}));}function intervals(id,items,total){$('#'+id).replaceChildren(...items.map(p=>{const row=document.createElement('div');row.className='interval';const bar=document.createElement('i');bar.style.left=(100*p.start/total)+'%';bar.style.width=(100*(p.end-p.start)/total)+'%';bar.className=p.cls||'';const label=document.createElement('span');label.textContent=p.label;row.append(bar,label);return row;}));}function plot(id,series,xr,yr,opts={}){const e=$('#'+id),X=x=>42+(x-xr[0])/(xr[1]-xr[0])*298,Y=y=>175-(y-yr[0])/(yr[1]-yr[0])*148;let out='<defs><clipPath id=\"clip-'+id+'\"><rect x=\"42\" y=\"27\" width=\"298\" height=\"148\"/></clipPath></defs>';for(let i=0;i<3;i++){let x=xr[0]+i*(xr[1]-xr[0])/2,y=yr[0]+i*(yr[1]-yr[0])/2;out+='<path class=\"gridline\" d=\"M '+X(x)+' 27V175M42 '+Y(y)+'H340\"/><text x=\"'+X(x)+'\" y=\"194\" text-anchor=\"middle\">'+esc(opts.xfmt?opts.xfmt(x):Number(x.toFixed(2)))+'</text><text x=\"36\" y=\"'+(Y(y)+4)+'\" text-anchor=\"end\">'+esc(opts.yfmt?opts.yfmt(y):Number(y.toFixed(2)))+'</text>';}out+='<g clip-path=\"url(#clip-'+id+')\">';for(const s of series){out+='<path fill=\"none\" stroke=\"'+(s.color||'var(--accent)')+'\" stroke-width=\"2.5\" '+(s.dash?'stroke-dasharray=\"5 4\"':'')+' d=\"'+s.pts.map((p,i)=>(i?'L':'M')+X(p[0]).toFixed(2)+','+Y(p[1]).toFixed(2)).join(' ')+'\"/>';}for(const p of opts.points||[])out+='<circle cx=\"'+X(p[0])+'\" cy=\"'+Y(p[1])+'\" r=\"4\" fill=\"var(--second)\" stroke=\"var(--paper)\" stroke-width=\"1.5\"/>';if(opts.cursor!==undefined)out+='<path d=\"M'+X(opts.cursor)+' 27V175\" stroke=\"var(--muted)\" stroke-dasharray=\"3 3\"/>';e.innerHTML=out+'</g>';e.dataset.curves=JSON.stringify(series.map(s=>s.pts));}const curve=(fn,lo,hi,n=120)=>Array.from({length:n+1},(_,i)=>{const x=lo+(hi-lo)*i/n;return[x,fn(x)]});function inputs(draw){document.querySelectorAll('input,select').forEach(e=>{e.addEventListener('input',draw);e.addEventListener('change',draw)});draw()}const n=id=>+$('#'+id).value;const show=(id,v,d=3)=>set(id,Number(v.toFixed(d)));function draw(){let h=n('head'),l=n('length'),a=Array.from({length:l},(_,i)=>String.fromCharCode(65+i)),cut=Math.min(l,8-h);set('head-value',h);set('length-value',l);cells('physical',Array.from({length:8},(_,j)=>{let i=(j-h+8)%8;return{text:j+': '+(i<l?a[i]:'—'),cls:i<l?(j>=h?'on':'gold'):'empty'}}));set('first','['+a.slice(0,cut).join(', ')+']');set('second','['+a.slice(cut).join(', ')+']');set('logical','['+a.join(', ')+']');set('explanation',t('explain'));}inputs(draw);","audio":false,"strings":{"explain":"青色是第一段,橙色是绕回开头的第二段;读取逻辑顺序时先接第一段再接第二段。","first":"as_slices().0","head":"头部物理位置","heading":"逻辑队列怎样跨过物理末端?","intro":"移动头部和长度,观察 as_slices 的两段如何拼成原顺序。","length":"队列长度","logical":"逻辑顺序","physical":"物理槽位","reset":"重置","scope":"固定容量 8 的环形模型,不承诺标准 VecDeque 的容量增长或内部字段表示。","scopeLabel":"模型范围与约定","second":"as_slices().1"}}
BinaryHeap:调度顺序是 Ord 的结果
标准 BinaryHeap 是最大堆;需要最早期限先执行,可以将比较键包装为 Reverse。若并列任务需要 FIFO,就在键中加入按入队顺序分配的序号,不能依赖内部排列顺序。
输入:deadline, sequence (20, 0), (10, 2), (10, 1) BinaryHeap Reverse((d, s)) 连续 pop 的顺序 (10, 1) → (10, 2) → (20, 0) 先比较期限,期限相同再比较序号 最早期限优先:Reverse 同时反转元组的比较顺序 序号必须来自明确的入队策略;堆本身不会自动提供相同优先级的 FIFO。
use std:: { cmp:: Reverse, collections:: BinaryHeap} ;
fn main ( ) {
let mut pending = BinaryHeap:: from( [
Reverse( ( 20 u64 , 0 u64 ) ) ,
Reverse( ( 10 , 2 ) ) ,
Reverse( ( 10 , 1 ) ) ,
] ) ;
assert_eq! ( pending.pop ( ) , Some ( Reverse( ( 10 , 1 ) ) ) ) ;
assert_eq! ( pending.pop ( ) , Some ( Reverse( ( 10 , 2 ) ) ) ) ;
assert_eq! ( pending.pop ( ) , Some ( Reverse( ( 20 , 0 ) ) ) ) ;
assert_eq! ( pending.pop ( ) , None ) ;
let mut scores = BinaryHeap:: from( [ 9 , 5 , 3 ] ) ;
{
let mut top = scores.peek_mut ( ) .unwrap ( ) ;
* top = 1 ;
} assert_eq! ( scores.peek ( ) , Some ( & 5 ) ) ;
}
序号的分配与回绕是调度器的责任;长寿命系统应在溢出前处理,而不是让重复序号悄悄改变顺序。真实任务可只把期限、序号和任务 ID 放在堆中,将大对象保存在独立表里,从而不让任务正文参与 Ord。
普通 iter 不提供排序遍历,连续 pop 才按堆优先级取出。也不要通过内部可变性悄悄修改堆中元素的排序字段;更新堆顶可以使用 peek_mut,任意任务改期则需要明确的删除/重插或版本化失效策略。后者允许旧条目留在堆中,弹出时检查版本并跳过,但必须控制陈旧条目的积累。BinaryHeap 契约
衡量真实成本
记录元素数、键分布、插删比例、容量峰值和是否要求输出顺序,再测试构建与稳态两个阶段。预分配降低扩容次数,但可能增加长期内存占用;shrink_to_fit 也不保证 RSS 立刻下降,后面还隔着分配器和操作系统。
使用集合的安全 API 不等于所有逻辑条件由编译器证明:索引有效性、业务 ID 生命周期、哈希一致性和排序规则仍是设计的一部分。