1
0
mirror of https://github.com/golang/go synced 2024-11-25 22:07:58 -07:00

vector cleanup:

- change Delete to Remove
- return deleted element in Remove
- remove range checking (runtime does this for you)

R=gri
OCL=14714
CL=14714
This commit is contained in:
Rob Pike 2008-09-02 13:16:43 -07:00
parent 9fbc221f0e
commit a0b2ccf9f4
2 changed files with 9 additions and 26 deletions

View File

@ -11,7 +11,7 @@ package vector
v := vector.New(); v := vector.New();
v.Insert(0, new(Foo)); v.Insert(0, new(Foo));
v.Append(new(Foo)); v.Append(new(Foo));
v.Delete(0); v.Remove(0);
for i := 0; i < v.Len(); i++ { f(v.At(i)); } for i := 0; i < v.Len(); i++ { f(v.At(i)); }
*/ */
@ -26,56 +26,39 @@ export type Vector struct {
export func New() *Vector { export func New() *Vector {
v := new(Vector); v := new(Vector);
v.elem = new([]Element, 1) [0 : 0]; // capacity must be > 0! v.elem = new([]Element, 8) [0 : 0]; // capacity must be > 0!
return v; return v;
} }
func (v *Vector) RangeError(op string, i int) {
panic("Vector.", op, ": index ", i, " out of range (len = ", len(v.elem), ")\n");
}
func (v *Vector) Len() int { func (v *Vector) Len() int {
return len(v.elem); return len(v.elem);
} }
func (v *Vector) At(i int) Element { func (v *Vector) At(i int) Element {
n := v.Len(); // range check unnecessary - done by runtime
if i < 0 || i >= n {
v.RangeError("At", i);
var e Element;
return e; // don't return nil - may not be legal in the future
}
return v.elem[i]; return v.elem[i];
} }
// TODO(r) It would be better if this were called 'Remove' and if func (v *Vector) Remove(i int) Element {
// it were returning the removed element. This way it would be ret := v.elem[i];
// symmetric with 'Insert', provide the functionality of 'Delete'
// and allow to get the appropriate entry w/ an extra call.
func (v *Vector) Delete(i int) {
n := v.Len(); n := v.Len();
if i < 0 || i >= n { // range check unnecessary - done by runtime
v.RangeError("Delete", i);
}
for j := i + 1; j < n; j++ { for j := i + 1; j < n; j++ {
v.elem[j - 1] = v.elem[j]; v.elem[j - 1] = v.elem[j];
} }
var e Element; var e Element;
v.elem[n - 1] = e; // don't set to nil - may not be legal in the future v.elem[n - 1] = e; // don't set to nil - may not be legal in the future
v.elem = v.elem[0 : n - 1]; v.elem = v.elem[0 : n - 1];
return ret;
} }
func (v *Vector) Insert(i int, e Element) { func (v *Vector) Insert(i int, e Element) {
n := v.Len(); n := v.Len();
if i < 0 || i > n { // range check unnecessary - done by runtime
v.RangeError("Insert", i);
}
// grow array by doubling its capacity // grow array by doubling its capacity
if n == cap(v.elem) { if n == cap(v.elem) {

View File

@ -50,7 +50,7 @@ func test1() {
} }
for v.Len() > 10 { for v.Len() > 10 {
v.Delete(10); v.Remove(10);
} }
} }