Skip to content

Commit f4621ca

Browse files
artagnonemberian
authored andcommitted
priority_queue: implement simple iterator
Remove PriorityQueue::each and replace it with PriorityQueue::iter, which ultimately calls into vec::VecIterator via PriorityQueueIterator. Implement iterator::Iterator for PriorityQueueIterator. Now you should be able to do: extern mod extra; let mut pq = extra::priority_queue::PriorityQueue::new(); pq.push(5); pq.push(6); pq.push(3); for pq.iter().advance |el| { println(fmt!("%d", *el)); } just like you iterate over vectors, hashmaps, hashsets etc. Note that the iteration order is arbitrary (as before with PriorityQueue::each), and _not_ the order you get when you pop() repeatedly. Add an in-file test to guard this. Reported-by: Daniel Micay <[email protected]> Signed-off-by: Ramkumar Ramachandra <[email protected]>
1 parent 2b17e47 commit f4621ca

File tree

1 file changed

+27
-4
lines changed

1 file changed

+27
-4
lines changed

src/libextra/priority_queue.rs

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,11 @@ impl<T:Ord> Mutable for PriorityQueue<T> {
3737
}
3838

3939
impl<T:Ord> PriorityQueue<T> {
40-
/// Visit all values in the underlying vector.
41-
///
42-
/// The values are **not** visited in order.
43-
pub fn each(&self, f: &fn(&T) -> bool) -> bool { self.data.iter().advance(f) }
40+
/// An iterator visiting all values in underlying vector, in
41+
/// arbitrary order.
42+
pub fn iter<'a>(&'a self) -> PriorityQueueIterator<'a, T> {
43+
PriorityQueueIterator { iter: self.data.iter() }
44+
}
4445

4546
/// Returns the greatest item in the queue - fails if empty
4647
pub fn top<'a>(&'a self) -> &'a T { &self.data[0] }
@@ -178,11 +179,33 @@ impl<T:Ord> PriorityQueue<T> {
178179
}
179180
}
180181

182+
/// PriorityQueue iterator
183+
pub struct PriorityQueueIterator <'self, T> {
184+
priv iter: vec::VecIterator<'self, T>,
185+
}
186+
187+
impl<'self, T> Iterator<&'self T> for PriorityQueueIterator<'self, T> {
188+
#[inline]
189+
fn next(&mut self) -> Option<(&'self T)> { self.iter.next() }
190+
}
191+
181192
#[cfg(test)]
182193
mod tests {
183194
use sort::merge_sort;
184195
use priority_queue::PriorityQueue;
185196

197+
#[test]
198+
fn test_iterator() {
199+
let data = ~[5, 9, 3];
200+
let iterout = ~[9, 5, 3];
201+
let pq = PriorityQueue::from_vec(data);
202+
let mut i = 0;
203+
for pq.iter().advance |el| {
204+
assert_eq!(*el, iterout[i]);
205+
i += 1;
206+
}
207+
}
208+
186209
#[test]
187210
fn test_top_and_pop() {
188211
let data = ~[2u, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1];

0 commit comments

Comments
 (0)