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,