代码之家  ›  专栏  ›  技术社区  ›  Jonas

如何使用第一个元素从BTreeMap中查找以两个元组为键的内容?

  •  1
  • Jonas  · 技术社区  · 1 年前

    我有一个 BTreeMap 其中我使用二元组密钥来存储项目, (String, i32) ,因此存储整数的映射类型为 BTreeMap<(String, i32), i32> .

    有没有一种方法可以通过使用二元组的第一个元素来查找元素?例如,某种形式的自定义范围?我该怎么做?

    举个简短的例子:

    use std::collections::BTreeMap;
    
    fn main() {
        let mut m : BTreeMap<(String, i32), i32> = BTreeMap::new();
        m.insert(("hello".to_string(), 12), 34);
        m.insert(("hello".to_string(), 4), 56);
        m.insert(("other".to_string(), 4), 44);
    
        let one_element = m.get(&("hello".to_string(), 12));
        println!("{:?}", one_element);
    
        // does not work, perhaps some custom range could be used?
        let all_hello = m.get(&("hello".to_string(), _));
    }
    
    1 回复  |  直到 1 年前
        1
  •  3
  •   cdhowie    1 年前

    您可以使用 BTreeMap::range 要执行此操作:

    let range = m.range(("hello".to_string(), i32::MIN)..=("hello".to_string(), i32::MAX));
    
    for item in range {
        println!("{:?}", item);
    }
    

    ( Playground )

    请注意,由于 Borrow trait有效,不幸的是,您必须分配两个字符串,一个用于范围的每一端。