【问题标题】:Advance next() to peek() with multipeek使用 multipeek 将 next() 推进到 peek()
【发布时间】:2020-06-07 23:36:21
【问题描述】:

我正在使用 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);
    }
}

游乐场link

【问题讨论】:

  • 只需 mp.skip(2);mp.nth(2)
  • 最小的例子可能过于简化了。我宁愿不跟踪查看了多少个字符,并且 skip() 和 nth() 导致 O(n) 遍历我已经查看过的 UTF-8 字符。
  • 也许可以做一个更好的例子,同样对于精确大小的迭代器应该是 O(1)
  • 试图澄清这个例子。

标签: rust


【解决方案1】:

也许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);
    }
}

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

MultiPeek 的成本要高得多:它必须维护一个可增长的“缓冲区”来存储被窥视的项目,以便以后可以交付它们。

【讨论】:

    猜你喜欢
    • 2016-10-07
    • 2017-05-23
    • 2015-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多