How to save HashMap and its Iterator of values ​​in the same structure?

I am working on an iterator adapter that uses HashMap internally. First, it maps all input iterator keys to a map and places them as appropriate. In the end, I want to iterate over the map values ​​marked as not matching.

Apparently, I need to save both the map and its Value Iterator (which stores the iteration state) in the same structure, but I cannot figure out how to do this.

Here is an example that does not match the input iterator so that everything is simple:

use std::collections::hash_map::{HashMap, Values,}; use std::hash::Hash; struct Foo<'a, K, V> where K: 'a + Hash + Eq, V: 'a + Clone, { map: HashMap<K, (V, bool)>, values: Values<'a, K, (V, bool)>, } impl<'a, K, V> Foo<'a, K, V> where K: 'a + Hash + Eq, V: 'a + Clone, { fn new<I>(it: I) -> Self where I: Iterator<Item=(K, V)> { // load the HashMap let mut map: HashMap<K, (V, bool)> = HashMap::new(); for (k, v) in it { map.insert(k, (v, false)); } // I cannot use `let values = map.values();` since map will be moved to Foo. Foo {map: map, values: ???} } } impl<'a, K, V> Iterator for Foo<'a, K, V> where K: 'a + Hash + Eq, V: 'a + Clone, { type Item = V; fn next(&mut self) -> Option<Self::Item> { match self.values.next() { loop { match some.values.next() { Some(v) if !v.1 => return Some(Clone::clone(&v.0)), Some(_) => continue, None => return None, } } } } } fn main() { let it = (0..).zip("AB".chars()); let foo = Foo::new(it); for v in foo { println!("{}", v); } } 

Thanks so much for any suggestions.

0
source share

Source: https://habr.com/ru/post/1235504/


All Articles