Is it possible to perform push!/pop!/deleteat! on an OffsetArray?


#1

Maybe I haven’t understood the usage of OffsetArray fully. I am porting some code from C++ and would like to have an 0-based indexing array on which one can still perform actions such as push! or delete! (i.e. the length is not fixed). Is this possible to achieve with OffsetArrays.jl or any other existing package? Or should I consider writing my own type extending AbstractArray.

The algorithm (which involves the depth of a tree) will be all over the place without 0-based indexing, which is quite annoying. Basically what I want is an array similar to the default array, with the only difference being that its index starts from 0.


#2

It’s not an operation that has a method defined, but you can do it manually:

julia> using OffsetArrays

julia> a = OffsetArray(collect(1:5), (-1,))
OffsetArray(::Array{Int64,1}, 0:4) with eltype Int64 with indices 0:4:
 1
 2
 3
 4
 5

julia> push!(a, 6)
ERROR: MethodError: no method matching push!(::OffsetArray{Int64,1,Array{Int64,1}}, ::Int64)
Closest candidates are:
  push!(::Any, ::Any, ::Any) at abstractarray.jl:2064
  push!(::Any, ::Any, ::Any, ::Any...) at abstractarray.jl:2065
  push!(::Array{Any,1}, ::Any) at array.jl:862
  ...
Stacktrace:
 [1] top-level scope at none:0

julia> push!(parent(a), 6)
6-element Array{Int64,1}:
 1
 2
 3
 4
 5
 6

julia> a
OffsetArray(::Array{Int64,1}, 0:5) with eltype Int64 with indices 0:5:
 1
 2
 3
 4
 5
 6

(A pull request to implement push! directly on an OffsetVector{T,N,<:Vector} would be merged if submitted.)