Ordered container clarification

From the push()! documentation:

Insert one or more items in collection . If collection is an ordered container, the items are inserted at the end (in the given order).

What does ordered mean is this case? That the collection preservers the insertion order? The example uses arrays, but arrays don’t sort as you insert the elements, and I can add elements to the end of an unsorted array:

unsorted_numbers = Int32[5,47,22,15,3,10]
push!(unsorted_numbers, 32)
println(unsorted_numbers)

Output:
[5, 47, 22, 15, 3, 10, 32]

That’s a way of phrasing it. But it really means what it says above. “Order” in this context does not imply sorting.

2 Likes

I’m not sure, but if you actually wanted sorted containers, they are here (none that I know of are in the standard library Base, meaning in Julia; that package can however be seen as the standard):
https://juliacollections.github.io/DataStructures.jl/v0.9/sorted_containers.html

Arrays (and lists, neither in Julia Base; available in the package above) are naturally ordered. Dicts (and sets), are often unordered, there’s are many different kinds, some unordered, some ordered, some sorted, while only unordered Dict and Set are in the standard library, meaning Julia Base.

For ordered dict, the most used is OrderedDict (while it’s not the fastest option).

E.g. unlike:

julia> d = Dict("A" => 1, "B" => 2)
Dict{String,Int64} with 2 entries:
  "B" => 2
  "A" => 1

You see it right away, this time, I guess you have a 50% change, for two values (it seems lower, just beware) of actually unordered, at least not for:

d = Dict("B" =>2, "C" => 3)
Dict{String,Int64} with 2 entries:
  "B" => 2
  "C" => 3

And deceptively push! seems to add to the end:

julia> push!(d, "C" => 3)
Dict{String,Int64} with 3 entries:
  "B" => 2
  "C" => 3

The pattern seems to hold adding for the next 3 push!, until:

julia> push!(d, "G" => 7)
Dict{String,Int64} with 7 entries:
  "B" => 2
  "C" => 3
  "D" => 4
  "G" => 7
  "E" => 5
  "F" => 6

No, it isn’t deceptive; Dict is not ordered and entries just happen to be printed some way. The concept of “end” does not apply here.

There is no pattern.

1 Like