mirror of
https://github.com/golang/go
synced 2024-11-22 05:44:41 -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:
parent
9fbc221f0e
commit
a0b2ccf9f4
@ -11,7 +11,7 @@ package vector
|
||||
v := vector.New();
|
||||
v.Insert(0, new(Foo));
|
||||
v.Append(new(Foo));
|
||||
v.Delete(0);
|
||||
v.Remove(0);
|
||||
for i := 0; i < v.Len(); i++ { f(v.At(i)); }
|
||||
*/
|
||||
|
||||
@ -26,56 +26,39 @@ export type Vector struct {
|
||||
|
||||
export func 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;
|
||||
}
|
||||
|
||||
|
||||
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 {
|
||||
return len(v.elem);
|
||||
}
|
||||
|
||||
|
||||
func (v *Vector) At(i int) Element {
|
||||
n := v.Len();
|
||||
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
|
||||
}
|
||||
// range check unnecessary - done by runtime
|
||||
return v.elem[i];
|
||||
}
|
||||
|
||||
|
||||
// TODO(r) It would be better if this were called 'Remove' and if
|
||||
// it were returning the removed element. This way it would be
|
||||
// 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) {
|
||||
func (v *Vector) Remove(i int) Element {
|
||||
ret := v.elem[i];
|
||||
n := v.Len();
|
||||
if i < 0 || i >= n {
|
||||
v.RangeError("Delete", i);
|
||||
}
|
||||
// range check unnecessary - done by runtime
|
||||
for j := i + 1; j < n; j++ {
|
||||
v.elem[j - 1] = v.elem[j];
|
||||
}
|
||||
var e Element;
|
||||
v.elem[n - 1] = e; // don't set to nil - may not be legal in the future
|
||||
v.elem = v.elem[0 : n - 1];
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
func (v *Vector) Insert(i int, e Element) {
|
||||
n := v.Len();
|
||||
if i < 0 || i > n {
|
||||
v.RangeError("Insert", i);
|
||||
}
|
||||
// range check unnecessary - done by runtime
|
||||
|
||||
// grow array by doubling its capacity
|
||||
if n == cap(v.elem) {
|
||||
|
@ -50,7 +50,7 @@ func test1() {
|
||||
}
|
||||
|
||||
for v.Len() > 10 {
|
||||
v.Delete(10);
|
||||
v.Remove(10);
|
||||
}
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user