1
0
mirror of https://github.com/golang/go synced 2024-11-22 03:24:41 -07:00

iterator for vector

R=rsc
DELTA=35  (35 added, 0 deleted, 0 changed)
OCL=26662
CL=26662
This commit is contained in:
Rob Pike 2009-03-23 17:46:59 -07:00
parent 482cbb1f33
commit 8d44052b6d
2 changed files with 35 additions and 0 deletions

View File

@ -210,3 +210,19 @@ func (p *Vector) Swap(i, j int) {
a := p.a;
a[i], a[j] = a[j], a[i]
}
// Iterate over all elements; driver for range
func (p *Vector) iterate(c chan Element) {
for i := 0; i < len(p.a); i++ {
c <- p.a[i]
}
close(c);
}
// Channel iterator for range.
func (p *Vector) Iter() chan Element {
c := make(chan Element);
go p.iterate(c);
return c;
}

View File

@ -139,6 +139,7 @@ func TestInsertVector(t *testing.T) {
verify_pattern(t, a, 8, 1000, 2);
}
func TestSorting(t *testing.T) {
const n = 100;
a := vector.NewIntVector(n);
@ -170,3 +171,21 @@ func TestDo(t *testing.T) {
t.Error("should visit", n, "values; did visit", count)
}
}
func TestIter(t *testing.T) {
const Len = 100;
x := vector.New(Len);
for i := 0; i < Len; i++ {
x.Set(i, i*i);
}
i := 0;
for v := range x.Iter() {
if v.(int) != i*i {
t.Error("Iter expected", i*i, "got", v.(int))
}
i++;
}
if i != Len {
t.Error("Iter stopped at", i, "not", Len)
}
}