在处理数据流时如何有效地构建向量和该向量的索引?

问题描述 投票:10回答:3

我有一个结构Foo

struct Foo {
    v: String,
    // Other data not important for the question
}

我想处理数据流并将结果保存到Vec<Foo>,并在字段Vec<Foo>上为此Foo::v创建一个索引。

我想为索引使用HashMap<&str, usize>,其中的键将为&Foo::v,值是Vec<Foo>中的位置,但我愿意接受其他建议。

我想尽可能快地处理数据流,这不需要做两次明显的事情。

例如,我想:

  • 每读取一个数据流仅分配一次String一次
  • 不两次搜索索引,一次不检查密钥,一次用于插入新密钥。
  • 不使用RcRefCell来增加运行时间。

借阅检查器不允许此代码:

let mut l = Vec::<Foo>::new();
{
    let mut hash = HashMap::<&str, usize>::new();
    //here is loop in real code, like: 
    //let mut s: String; 
    //while get_s(&mut s) {
    let s = "aaa".to_string();
    let idx: usize = match hash.entry(&s) { //a
        Occupied(ent) => {
            *ent.get()
        }
        Vacant(ent) => {
            l.push(Foo { v: s }); //b
            ent.insert(l.len() - 1);
            l.len() - 1
        }
    };
    // do something with idx
}

存在多个问题:

  1. [hash.entry借用密钥,因此s的生存期必须比hash大”
  2. 我想在行(b)处移动s,而我在行(a)处具有只读引用
  3. 所以我应该如何实现这种简单的算法而又不需额外调用String::clone或在调用HashMap::get之后再调用HashMap::insert

我有一个struct Foo:struct Foo {v:字符串,//对这个问题不重要的其他数据}我想处理数据流并将结果保存到Vec 并创建索引...

rust move-semantics lifetime borrowing
3个回答
8
投票

一般


5
投票

不使用RcRefCell来增加运行时间。


1
投票

错误是:

© www.soinside.com 2019 - 2024. All rights reserved.