From dc2d99250d7ae5337af2aed2b4cc8e6fd11ab5e0 Mon Sep 17 00:00:00 2001 From: Harrison McCullough Date: Tue, 15 Oct 2019 20:20:29 -0600 Subject: [PATCH] Implement iter_counts The `iter` method returns an iterator that returns each key the appropriate number of times. The new `iter_counts` method returns an iterator that returns tuples that contain the key and the number of times it appears. --- src/multiset.rs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/multiset.rs b/src/multiset.rs index dacaec8..784dc7f 100644 --- a/src/multiset.rs +++ b/src/multiset.rs @@ -108,6 +108,29 @@ where } } + /// An iterator visiting all elements in arbitrary order paired with the number of times the + /// item appears. + /// The iterator element type is `(&'a K, usize)`. + /// + /// # Examples + /// + /// ``` + /// use multiset::HashMultiSet; + /// let mut multiset = HashMultiSet::new(); + /// multiset.insert(0); + /// multiset.insert(0); + /// multiset.insert(1); + /// + /// let mut keys_with_counts: Vec<_> = multiset.iter_counts().collect(); + /// keys_with_counts.sort(); // Order is arbitrary + /// assert_eq!(keys_with_counts, vec![(&0, 2), (&1, 1)]); + /// ``` + pub fn iter_counts(&self) -> IterCounts { + IterCounts { + iter: self.elem_counts.iter(), + } + } + /// Returns true if the multiset contains no elements. /// /// # Examples @@ -342,6 +365,18 @@ where } } +pub struct IterCounts<'a, K> { + iter: hash_map::Iter<'a, K, usize>, +} + +impl<'a, K> Iterator for IterCounts<'a, K> { + type Item = (&'a K, usize); + + fn next(&mut self) -> Option { + self.iter.next().map(|(key, &count)| (key, count)) + } +} + impl Add for HashMultiSet where T: Eq + Hash + Clone,