SortStructuredArray SortStructuredList with string array()[]

Share your advanced PureBasic knowledge/code with the community.
User avatar
Keya
Addict
Addict
Posts: 1890
Joined: Thu Jun 04, 2015 7:10 am

SortStructuredArray SortStructuredList with string array()[]

Post by Keya »

It doesn't seem possible to use the excellent SortStructuredArray/List functions with string arrays in a structure, because the OffsetOf() function doesn't seem to like arrays of either () or [] form. I don't think i've worded that very well but here's an example...

For example, this is valid (where ColTxt$ is a single string variable):
SortStructuredList(Rows(0)\Animals(), 0, OffsetOf(Animal\ColTxt$), TypeOf(Animal\ColTxt$))

These aren't valid (where ColTxt$(3) or ColTxt$[3] are arrays) and generate compiler error:
SortStructuredList(Rows(0)\Animals(), 0, OffsetOf(Animal\ColTxt$(3)), TypeOf(Animal\ColTxt$))
SortStructuredList(Rows(0)\Animals(), 0, OffsetOf(Animal\ColTxt$[3]), TypeOf(Animal\ColTxt$))

However, because the strings in the structure are just pointers the Sort can still be used, simply with a hardcoded "+ (offset * SizeOf(Integer))":
SortStructuredList(Rows(0)\Animals(), 0, OffsetOf(Animal\ColTxt$) + (3 * SizeOf(Integer)), TypeOf(Animal\ColTxt$))

I've found this provides a lot of flexibility when more than one dynamic list is required.

rough example:

Code: Select all

Structure Animal
  ColTxt$[4]
  Speed.l
EndStructure

Structure ROWS
  List Animals.Animal()
EndStructure

Global Dim ROWS.ROWS(5)

AddElement(Rows(0)\Animals())
Rows(0)\Animals()\ColTxt$[0] = "alpha"
Rows(0)\Animals()\ColTxt$[1] = "CAPPA"
Rows(0)\Animals()\Speed = 30

AddElement(Rows(0)\Animals())
Rows(0)\Animals()\ColTxt$[0] = "beta"
Rows(0)\Animals()\ColTxt$[1] = "BETA"
Rows(0)\Animals()\Speed = 10

AddElement(Rows(0)\Animals())
Rows(0)\Animals()\ColTxt$[0] = "cappa"
Rows(0)\Animals()\ColTxt$[1] = "ALPHA"
Rows(0)\Animals()\Speed = 20

SortStructuredList(Rows(0)\Animals(), 0, OffsetOf(Animal\ColTxt$) + (1 * SizeOf(Integer)) , TypeOf(Animal\ColTxt$))  ;index [1]
;                                                              ___^^___               
ForEach Rows(0)\Animals()
  Debug Rows(0)\Animals()\ColTxt$[0]+": "+Str(Rows(0)\Animals()\Speed)
Next
User avatar
Thunder93
Addict
Addict
Posts: 1788
Joined: Tue Mar 21, 2006 12:31 am
Location: Canada

Re: SortStructuredArray SortStructuredList with string array

Post by Thunder93 »

Nice Keya. Thanks for sharing. :P
ʽʽSuccess is almost totally dependent upon drive and persistence. The extra energy required to make another effort or try another approach is the secret of winning.ʾʾ --Dennis Waitley
davido
Addict
Addict
Posts: 1890
Joined: Fri Nov 09, 2012 11:04 pm
Location: Uttoxeter, UK

Re: SortStructuredArray SortStructuredList with string array

Post by davido »

@Keya,

Very nice!
Thank you for sharing.
DE AA EB
Post Reply