使用 multipeek 将 next() 推进到 peek()

srk*_*ing 1 rust

我正在使用 Rust Itertools MultiPeek。如何有效或方便地将 next() 迭代器前进到 peek() 迭代器的当前位置?

fn main() {
    let v = "abcd";
    let mut mp = itertools::multipeek(v.char_indices());
    if let Some((byte_offset, c)) = mp.peek() {
        println!("peek: offset {}, char {}", byte_offset, c);
    }
    if let Some((byte_offset, c)) = mp.peek() {
        println!("peek: offset {}, char {}", byte_offset, c);
    }

    // Update next to current location of peek assuming
    // we'd rather not keep track the number of peeks

    if let Some((byte_offset, c)) = mp.next() {
        // would like to have Offset 2, char c
        println!("next: offset {}, char {}", byte_offset, c);
    }
}
Run Code Online (Sandbox Code Playgroud)

游乐场链接

har*_*mic 5

也许MultiPeek根本不能解决您的问题。

听起来您正在遍历一个字符串,并且在某些时候,您需要向前看一点。根据您所看到的内容,您要么继续前进,要么回到开始“偷看”之前的位置。

MultiPeek您可以在需要开始向前查找的位置克隆正在使用的迭代器,而不是使用。然后,当您看得足够远时,您可以删除克隆并继续使用原始迭代器,或者删除原始迭代器并使用克隆。也许是这样的:

fn main() {
    let v = "abcd";
    let mut iter = v.char_indices();
    let iter_save = iter.clone();
    if let Some((byte_offset, c)) = iter.next() {
        println!("peek: offset {}, char {}", byte_offset, c);
    }
    if let Some((byte_offset, c)) = iter.next() {
        println!("peek: offset {}, char {}", byte_offset, c);
    }

    // Here we decide if we are going back to the 'save' point or continuing
    // on forward (for this example I assume we are rewinding)
    let mut iter = if true {
        iter_save
    } else {
        iter
    };

    if let Some((byte_offset, c)) = iter.next() {
        println!("next: offset {}, char {}", byte_offset, c);
    }
}
Run Code Online (Sandbox Code Playgroud)

CharIndices大多数迭代器的克隆成本相对较低 - 在它看起来包含一个和两个指针的情况下usize

MultiPeek成本要高得多:它必须为所查看的项目维护一个可增长的“缓冲区”,以便以后可以将它们传送出去。