Array
containers.Array( of T ) is a list that grows. Push adds an element at the
end; when the storage is full it doubles, so a long run of pushes reallocates
only a few times. Use it instead of growing an ordinary array one element at a
time with redim preserve.
#import "std/containers"
sub Show( byref label as ustring, byref xs as containers.Array( of int32 ) )
print label; ":";
for each x in xs
print x;
next
print " (count"; xs.Count( ); ")"
end sub
'' A brace list gives the starting elements.
dim xs as containers.Array( of int32 ) = { 5, 3, 9 }
Show( "start", xs )
xs.Push( 7 ) '' append at the end
Show( "push 7", xs )
'' Indices start at 0, and xs[ i ] can be assigned.
print "first"; xs[ 0 ]; ", last"; xs[ xs.Count( ) - 1 ]
xs[ 1 ] = 30
Show( "xs[1] = 30", xs )
print "pop gives"; xs.Pop( ) '' remove and return the last
Show( "after pop", xs )
xs.Insert( 0, 1 ) '' shifts the rest along
Show( "insert 1 at 0", xs )
xs.Remove( 2 ) '' closes the gap, keeps the order
Show( "remove at 2", xs )
'' for each byref changes the elements in place.
for each byref x in xs
x *= 2
next
Show( "doubled", xs )
xs.Clear( )
print "empty now: "; xs.IsEmpty( ); ", pop of empty gives"; xs.Pop( )
Output
start: 5 3 9 (count 3)
push 7: 5 3 9 7 (count 4)
first 5, last 7
xs[1] = 30: 5 30 9 7 (count 4)
pop gives 7
after pop: 5 30 9 (count 3)
insert 1 at 0: 1 5 30 9 (count 4)
remove at 2: 1 5 9 (count 3)
doubled: 2 10 18 (count 3)
empty now: true, pop of empty gives 0
Indices start at 0: xs[ 0 ] is the first element and
xs[ xs.Count( ) - 1 ] the last. xs[ i ] can be read and assigned.
| Member | Does |
|---|---|
Push( v ), Pop( ) | add at the end; remove and return the last |
Insert( i, v ), Remove( i ) | add or remove at i, keeping the order |
RemoveSwap( i ) | remove at i by moving the last element into the gap |
Count( ), IsEmpty( ) | how many elements there are |
Capacity( ), Reserve( n ), Shrink( ) | the storage behind them |
Clear( ) | remove every element, keeping the storage |
Insert and Remove move every element after i, so they cost more the
longer the array is. RemoveSwap is the fast way to remove when the order does
not matter.
for each x in xs gives you a copy of each element; for each byref x in xs
gives you the element itself, so assigning to x changes the array. Pop on
an empty array returns the element type's default value, 0 here, rather than
failing: check IsEmpty( ) first when that matters.
Under -exx, xs[ i ] is checked against the array's storage, not against
Count( ). An index past the last element but inside the capacity reads a
stale value instead of stopping the program:
dim xs as containers.Array( of int32 ) = { 1, 2, 3, 4 }
xs.Pop( )
print xs[ 3 ] '' prints 4; Count( ) is 3
Keep indices below Count( ) yourself.
Activities
- Use
RemoveSwap( 0 )instead ofRemove( 2 )and compare the order. - Push the numbers 1 to 100 and print
Capacity( )after every tenth push.