Using System.Move() to insert/delete item(s) from an array of string is not as easy as insert/delete it from other array of simple data types. The problem is ... string is reference counted in Delphi. Using Move() on reference-counted data types needs deeper knowledge on internal compiler behaviour.
Can someone here explain the needed steps for me to achieve that, or better with some snippet codes, or direct me to a good reference on the internet?
Oh, Please don't tell me to use the "lazy-but-slow way", that is, for loop, I know that.
I've demonstrated how to delete items from a dynamic array before:
Delphi Q&A: How do I delete an element from an array?
In that article, I start with the following code:
type
TXArray = array of X;
procedure DeleteX(var A: TXArray; const Index: Cardinal);
var
ALength: Cardinal;
i: Cardinal;
begin
ALength := Length(A);
Assert(ALength > 0);
Assert(Index < ALength);
for i := Index + 1 to ALength - 1 do
A[i - 1] := A[i];
SetLength(A, ALength - 1);
end;
You cannot go wrong with that code. Use whatever value for X you want; in your case, replace it with string. If you want to get fancier and use Move, then there's way to do that, too.
procedure DeleteX(var A: TXArray; const Index: Cardinal);
var
ALength: Cardinal;
TailElements: Cardinal;
begin
ALength := Length(A);
Assert(ALength > 0);
Assert(Index < ALength);
Finalize(A[Index]);
TailElements := ALength - Index;
if TailElements > 0 then
Move(A[Index + 1], A[Index], SizeOf(X) * TailElements);
Initialize(A[ALength - 1]);
SetLength(A, ALength - 1);
end;
Since X is string, the Finalize call is equivalent to assigning the empty string to that array element. I use Finalize in this code, though, because it will work for all array-element types, even types that include records, interfaces, strings, and other arrays.
For inserting, you just shift things the opposite direction:
procedure InsertX(var A: TXArray; const Index: Cardinal; const Value: X);
var
ALength: Cardinal;
TailElements: Cardinal;
begin
ALength := Length(A);
Assert(Index <= ALength);
SetLength(A, ALength + 1);
Finalize(A[ALength]);
TailElements := ALength - Index;
if TailElements > 0 then begin
Move(A[Index], A[Index + 1], SizeOf(X) * TailElements);
Initialize(A[Index]);
A[Index] := Value;
end;
Use Finalize when you're about to do something that's outside the bounds of the language, such as using the non-type-safe Move procedure to overwrite a variable of a compiler-managed type. Use Initialize when you're re-entering the defined part of the language. (The language defines what happens when an array grows or shrinks with SetLength, but it doesn't define how to copy or delete strings without using a string-assignment statement.)
You don't state if it is important for you to keep the array elements in the same order or not.
If the order is not relevant, you can so something really really fast like this:
procedure RemoveRecord(Index: integer);
begin
FRecords[Index]:= FRecords[High(FRecords)]; { Copy the last element over the 'deleted' element }
SetLength(FRecords, Length(FRecords)-1); { Cut the last element }
end;
{ I haven't tested the code to see it compiles, but you got the idea anyway... }
Sorting the list
If you have a HUGE list that needs to be modified by the user, you can use methods similar to the one above (break the list order). When the user its done editing (after multiple deletes), you present it with a button called "Sort list". Now he can do the lengthy (sort) operation.
Of course, I assume above that your list can be sorted by a certain parameter.
Sorting the list automatically
An alternative is to automate the sorting process. When the user deleted stuff from the list, start a timer. Keep resetting the timer if the user keeps deleting items. When the timer manages to trigger an event, do the sorting, stop the timer.
To insert a string, simply add a string (the lazy way) to the end of the array (which is an array of pointers), and then use Move to change the order of the elements of this array (of pointers).
If I wanted to insert a string into the middle of a list of strings, I'd use TStringList.Insert. (It does it quickly using System.Move.)
Any particular reason why you're using an array instead of a TStringList?
Call UniqueString() on it, before messing with it.
http://docwiki.embarcadero.com/VCL/en/System.UniqueString
Then you have a string with a single reference.
Fat chance that that is what delete and insert do too, and I doubt you'll be faster.
Just wanting to add this for any people that come here in the future.
Modifying Rob's code, I came up with this way of doing it that uses the newer TArray<T> type constructions.
type
TArrayExt = class(TArray)
class procedure Delete<T>(var A: TArray<T>; const Index: Cardinal; Count: Cardinal = 1);
end;
implementation
class procedure TArrayExt.Delete<T>(var A: TArray<T>; const Index: Cardinal;
Count: Cardinal = 1);
var
ALength: Cardinal;
i: Cardinal;
begin
ALength := Length(A);
Assert(ALength > 0);
Assert(Count > 0);
Assert(Count <= ALength - Index);
Assert(Index < ALength);
for i := Index + Count to ALength - 1 do
A[i - Count] := A[i];
SetLength(A, ALength - Count);
end;
A similar thing can be done for the insert.
(Not looking for this to get marked as the answer, just looking to provide an example that was too long to fit in the comments on Rob's excellent answer.)
(Fixed to address Rob's comments below.)
Move() works fine with reference counted types like strings or interfaces, and actually used internally in Delphi's arrays and lists. But, now, in general case, Move() is no longer valid because of managed records feature.
If you use System.Move to put items into an array of string, you should be aware that the strings that where there before the Move (and now overwritten), had a reference count of either -1 for constant strings, or > 0 for variable strings. Constant strings should not be altered, but variable strings should be treated accordingly: You should manually lower their reference-count (before they're overwritten!). To do that, you should try something like this:
Dec(PStrRec(IntPtr(SomeString)-12).refCnt);
But if the reference-count reached zero, you should also finalize the associated memory - something Delphi itself does a whole lot better if you let it work it's compiler-magic for strings. Oh, and also : if the strings you're copying come from the same array as your writing into, the needed administration becomes very cumbersome, very quickly!
So if it's in some way possible to avoid all this manual housekeeping, I would advise to let Delphi handle it itself.
Related
I'm working on a vintage code base and I am very new to delphi, so apologies in advance if my syntax is off a bit (or just plain wrong).
I have things like a pre defined (at compile time) array. arr and we used all over the place
file1.pas: arr[1] := 3.14
file2.pas: pi := arr[1]
And I've noticed that we never,ever use constants to access elements in the array. In C I would write:
int arr[100] = {0};
const int MY_INDEX=1;
arr[MY_INDEX] = 3.14
etc. But I don't see that in my delphi code base. Is that because Delphi/Pascal doesn't support it or because the original authors decided not to do it?
Thanks
Delphi allows you to use a constant as an array index. So if you don't see such a thing in your code, it's because the authors elected not to declare and use constants for array indices.
Yes constants can be used along with any expression that evaluates to an appropriate and valid index for the array. You should also note that an array in Delphi could be declared with a non-zero based index range:
var
MonthlyTotals: array[1..12] of Integer; // Jan = 1, Feb = 2 etc etc
You can even specify the index of an array as an enum type and use enum members for the indices which provides even tighter safety (where possible and appropriate), as per this contrived example:
type
TFileFormat = (ffXML, ffCSV, ffText, ffJSON);
var
sExtensions: array[TFileFormat] of String;
sExtensions[ffXML] := 'xml';
sExtensions[ffCSV] := 'csv';
sExtensions[ffText] := 'txt';
sExtensions[ffJSON] := 'json';
In such cases the array might only have members for certain (contiguous) values in the enum:
var
sExtensions: array[ffXML..ffCSV] of String;
For this reason, and the fact that array indices may not be zero based, unless you are 110% certain of the index range of an array it is a good idea to always use Low() and High() to determine the index bounds when iterating over the contents of an array and not assume the index basis:
// This will not work properly:
for i := 0 to 11 do
MonthlyTotals[i] := ....
// Neither will this, even though it looks more safe
for i := 0 to Pred(Length(MonthlyTotals)) do
MonthlyTotals[i] := ....
// This will be safe:
for i := Low(MonthlyTotals) to High(MonthlyTotals) do
MonthlyTotals[i] := ....
// And it works for enum indices as well:
for ext := Low(sExtensions) to High(sExtensions) do
sExtensions[ext] := ....
The exact conversion of your C code in Delphi would be along the lines of:
var
arr: array[100] of integer;
const
MY_INDEX = 1;
begin
arr[MY_INDEX] := 3.14;
end;
As others have said, perfectly feasible and the enum method is arguably a better alternative. One gotcha here is that this is relying on Delphi having the array initialised zeroed rather than setting it explicitly as in C.
How would I read data from a text file into two arrays? One being string and the other integer?
The text file has a layout like this:
Hello
1
Test
2
Bye
3
Each number corresponds to the text above it. Can anyone perhaps help me? Would greatly appreciate it
var
Items: TStringList;
Strings: array of string;
Integers: array of Integer;
i, Count: Integer;
begin
Items := TStringList.Create;
try
Items.LoadFromFile('c:\YourFileName.txt');
// Production code should check that Items.Count is even at this point.
// Actual arrays here. Set their size once, because we know already.
// growing your arrays inside the iteration will cause many reallocations
// and memory fragmentation.
Count := Items.Count div 2;
SetLength(Strings, Count);
SetLength(Integers, Count);
for i := 0 to Count - 1 do
begin
Strings[i] := Items[i*2];
Integers[i] := StrToInt(Items[i*2+1]);
end;
finally
Items.Free;
end;
end
I would read the file into a string list and then process it item by item. The even ones are put into the list of strings, and the odd ones go into the numbers.
var
file, strings, numbers: TStringList;
...
//create the lists
file.LoadFromFile(filename);
Assert(file.Count mod 2=0);
for i := 0 to file.Count-1 do
if i mod 2=0 then
strings.Add(file[i])
else
numbers.Add(file[i]);
I'd probably use some helper functions called odd and even in my own code.
If you wanted the numbers in a list of integers, rather than a string list, then you would use TList<Integer> and add StrToInt(file[i]) on the odd iterations.
I've used lists rather than dynamic arrays for the ease of writing this code, but GolezTrol shows you how to do it with dynamic arrays if that's what you prefer.
That said, since your state that the number is associated with the string, you may actually be better off with something like this:
type
TNameAndID = record
Name: string;
ID: Integer;
end;
var
List: TList<TNameAndID>;
Item: TNameAndID;
...
List := TList<TNameAndID>.Create;
file.LoadFromFile(filename);
Assert(file.Count mod 2=0);
for i := 0 to file.Count-1 do begin
if i mod 2=0 then begin
Item.Name := file[i];
end else begin
Item.ID := StrToInt(file[i]);
List.Add(Item);
end;
end;
end;
The advantage of this approach is that you now have assurance that the association between name and ID will be maintained. Should you ever wish to sort, insert or remove items then you will find the above structure much more convenient than two parallel arrays.
I implemented language translation in an application by putting all strings at runtime in a TStringList with:
procedure PopulateStringList;
begin
EnglishStringList.Append('CAN_T_FIND_FILE=It is not possible to find the file');
EnglishStringList.Append('DUMMY=Just a dummy record');
// total of 2000 record appended in the same way
EnglishStringList.Sorted := True; // Updated comment: this is USELESS!
end;
Then I get the translation using:
function GetTranslation(ResStr:String):String;
var
iIndex : Integer;
begin
iIndex := -1;
iIndex := EnglishStringList.IndexOfName(ResStr);
if iIndex >= 0 then
Result := EnglishStringList.ValueFromIndex[iIndex] else
Result := ResStr + ' (Translation N/A)';
end;
Anyway with this approach it takes about 30 microseconds to locate a record, is there a better way to achieve the same result?
UPDATE: For future reference I write here the new implementation that uses TDictionary as suggested (works with Delphi 2009 and newer):
procedure PopulateStringList;
begin
EnglishDictionary := TDictionary<String, String>.Create;
EnglishDictionary.Add('CAN_T_FIND_FILE','It is not possible to find the file');
EnglishDictionary.Add('DUMMY','Just a dummy record');
// total of 2000 record appended in the same way
end;
function GetTranslation(ResStr:String):String;
var
ValueFound: Boolean;
begin
ValueFound:= EnglishDictionary.TryGetValue(ResStr, Result);
if not ValueFound then Result := Result + '(Trans N/A)';
end;
The new GetTranslation function performs 1000 times faster (on my 2000 sample records) then the first version.
THashedStringList should be better, I think.
In Delphi 2009 or later I would use TDictionary< string,string > in Generics.Collections.
Also note that there are free tools such as http://dxgettext.po.dk/ for translating applications.
If THashedStringList works for you, that's great. Its biggest weakness is that every time you change the contents of the list, the Hash table is rebuilt. So it will work for you as long as your list remains small or doesn't change very often.
For more info on this, see: THashedStringList weakness, which gives a few alternatives.
If you have a big list that may be updated, you might want to try GpStringHash by gabr, that doesn't have to recompute the whole table at every change.
I think that you don't use the EnglishStringList(TStringList) correctly. This is a sorted list, you add elements (strings), you sort it, but when you search, you do this by a partial string (only the name, with IndexOfName).
If you use IndexOfName in a sorted list, the TStringList can't use Dicotomic search. It use sequential search.
(this is the implementation of IndexOfName)
for Result := 0 to GetCount - 1 do
begin
S := Get(Result);
P := AnsiPos('=', S);
if (P <> 0) and (CompareStrings(Copy(S, 1, P - 1), Name) = 0) then Exit;
end;
I think that this is the reason of poor performance.
The alternative is use 2 TStringList:
* The first (sorted) only containts the "Name" and a pointer to the second list that contain the value; You can implement this pointer to the second list using the "pointer" of Object property.
* The second (not sorted) list containt the values.
When you search, you do it at first list; In this case you can use the Find method. when you find the name, the pointer (implemented with Object property) give you the position on second list with the value.
In this case, Find method on Sorted List is more efficient that HashList (that must execute a funcion to get the position of a value).
Regards.
Pd:Excuse-me for mistakes with english.
You can also use a CLASS HELPER to re-program the "IndexOfName" function:
TYPE
TStringsHelper = CLASS HELPER FOR TStrings
FUNCTION IndexOfName(CONST Name : STRING) : INTEGER;
END;
FUNCTION TStringsHelper.IndexOfName(CONST Name : STRING) : INTEGER;
VAR
SL : TStringList ABSOLUTE Self;
S,T : STRING;
I : INTEGER;
BEGIN
IF (Self IS TStringList) AND SL.Sorted THEN BEGIN
S:=Name+NameValueSeparator;
IF SL.Find(S,I) THEN
Result:=I
ELSE IF (I<0) OR (I>=Count) THEN
Result:=-1
ELSE BEGIN
T:=SL[I];
IF CompareStrings(COPY(T,1,LENGTH(S)),S)=0 THEN Result:=I ELSE Result:=-1
END;
EXIT
END;
Result:=INHERITED IndexOfName(Name)
END;
(or implement it in a descendant TStrings class if you dislike CLASS HELPERs or don't have them in your Delphi version).
This will use a binary search on a sorted TStringList and a sequential search on other TStrings classes.
I wrote two methods with a void type parameter:
procedure Method1(const MyVar; size: cardinal);
var
Arr: array of byte;
begin
SetLength(Arr, size);
{now copy the data from MyVar to Arr, but how?}
end;
procedure Method2(var MyVar; size: cardinal);
var
Arr: array of byte;
begin
SetLength(Arr, size);
{return the data from the array, but how?}
end;
In the first one I would like to access the MyVar as an array of byte. In the second one, I would like to copy the data from the local array Arr to MyVar. Therefore I used the CopyMemory() function, but something is wrong with it.
If I use the following in the second method, it is fine as long as Method2 is called with an array as its parameter (Method2(Pointer(MyString)^, Length(MyString)) or Method2(Pointer(MyArray), Length(MyArray))).
CopyMemory(Pointer(MyVar), Pointer(Arr), size);
If I call Method2 with a, for instance, integer parameter (Method2(MyInteger, SizeOf(MyInteger))), it does not work properly. In this case, the CopyMemory() has to be called this way:
CopyMemory(#MyVar, Pointer(Arr), size);
How to return data from Method2 correctly not knowing whether it is a simple type (or record) or an array? The situation will be similar in Method1, but here I would have to use
CopyMemory(Pointer(Arr), Pointer(MyVar), size);
in case of arrays and
CopyMemory(Pointer(Arr), #MyVar, size);
in case of simple types.
What can I do about it when I don't know what the MyVar parameter is?
There's no such thing a a void type in Delphi. What you're referring to is called an untyped parameter.
An untyped parameter is always the actual thing itself, not a pointer to the thing you're supposed to use. Therefore, the correct way to use CopyMemory with such a parameter is to apply the # operator to it, like so:
CopyMemory(#MyVar, #Arr[0], size);
Notice I've also changed the way I pass the second parameter. It's better if you don't rely on the fact that a dynamic array is really a pointer to the first element. If you need a pointer to the first element, just say so explicitly, like I did here.
Your confusion comes from a test you made where the parameter was used as though it were a pointer, and the test appeared to work. I doubt the validity of that test, though. When you said Pointer(MyString)^, what you had was the first character of the string. When you then said Pointer(MyVar) inside the function, you were type-casting that character into a pointer, which was an invalid type-cast. If your program appeared to work, then it was only by accident; your code was wrong.
The best advice I can give is to not type-cast stuff unless you really have to. And when you do, please be sure that the thing you're type-casting really does have that type. In your case, you don't need to type-cast anything before you pass it as an untyped parameter. You can call Method1 like this:
Method1(MyString[1], Length(MyString) * Sizeof(Char));
(I multiply by SizeOf(Char) since I don't know whether you have Delphi 2009 or not.)
Also, do avoid untyped parameters. One of the great things a compiler can do to help ensure program correctness is to enforce type safety, but when you take away the types, the compiler can't help you anymore.
Your problem is that you pass either data OR pointer to a data to Method1/2. You should always pass data itself.
May be you just forgot that dynamic array is a pointer itself? You should not pass A or Pointer(A) in your methods (A is dynamic array here). Pass A[0] or Pointer(A)^.
procedure Method1(const MyVar; size: cardinal);
var
Arr: array of byte;
begin
SetLength(Arr, size);
CopyMemory(Pointer(Arr), #MyVar, Size);
end;
procedure Method2(var MyVar; size: cardinal);
var
Arr: array of byte;
begin
SetLength(Arr, size);
Arr[0] := 1;
Arr[1] := 2;
Arr[2] := 3;
Arr[3] := 4;
CopyMemory(#MyVar, Pointer(Arr), Size);
end;
procedure TForm1.FormCreate(Sender: TObject);
var
I: Integer;
A: array of Integer;
begin
I := $01020304;
Method1(I, 4); // we pass data itself, not the pointer to it.
Method2(I, 4);
SetLength(A, 2);
A[0] := 0;
A[1] := $01020304;
Method1(A[0], Length(A) * SizeOf(A[0])); // note, that we pass data, not pointer
Method2(A[0], Length(A) * SizeOf(A[0])); // A or Pointer(A) is a pointer to array's data
end;
If A is dynamic array:
A[0] is the same as Pointer(A)^ and represents array's data.
#A[0] is the same as Pointer(A) or just A and represents the array itself, which is pointer to it's data (and some tech info on negative offsets).
If A is static array:
A[0] is the same as A and represents the array itself, which is array's data.
#A[0] is the same as #A and represents the pointer to array.
Pointer(A) or Pointer(A)^ are meaningless.
Note, that Arr in Method1/2 is a dynamic array too, that is why we cast it to pointer (CopyMemory asks pointers, not the data). If we want to use Move routine (which asks data), we should write Pointer(A)^ instead.
Say I have an array of records which I want to sort based on one of the fields in the record. What's the best way to achieve this?
TExample = record
SortOrder : integer;
SomethingElse : string;
end;
var SomeVar : array of TExample;
You can add pointers to the elements of the array to a TList, then call TList.Sort with a comparison function, and finally create a new array and copy the values out of the TList in the desired order.
However, if you're using the next version, D2009, there is a new collections library which can sort arrays. It takes an optional IComparer<TExample> implementation for custom sorting orders. Here it is in action for your specific case:
TArray.Sort<TExample>(SomeVar , TDelegatedComparer<TExample>.Construct(
function(const Left, Right: TExample): Integer
begin
Result := TComparer<Integer>.Default.Compare(Left.SortOrder, Right.SortOrder);
end));
(I know this is a year later, but still useful stuff.)
Skamradt's suggestion to pad integer values assumes you are going to sort using a string compare. This would be slow. Calling format() for each insert, slower still. Instead, you want to do an integer compare.
You start with a record type:
TExample = record
SortOrder : integer;
SomethingElse : string;
end;
You didn't state how the records were stored, or how you wanted to access them once sorted. So let's assume you put them in a Dynamic Array:
var MyDA: Array of TExample;
...
SetLength(MyDA,NewSize); //allocate memory for the dynamic array
for i:=0 to NewSize-1 do begin //fill the array with records
MyDA[i].SortOrder := SomeInteger;
MyDA[i].SomethingElse := SomeString;
end;
Now you want to sort this array by the integer value SortOrder. If what you want out is a TStringList (so you can use the ts.Find method) then you should add each string to the list and add the SortOrder as a pointer. Then sort on the pointer:
var tsExamples: TStringList; //declare it somewhere (global or local)
...
tsExamples := tStringList.create; //allocate it somewhere (and free it later!)
...
tsExamples.Clear; //now let's use it
tsExamples.sorted := False; //don't want to sort after every add
tsExamples.Capacity := High(MyDA)+1; //don't want to increase size with every add
//an empty dynamic array has High() = -1
for i:=0 to High(MyDA) do begin
tsExamples.AddObject(MyDA[i].SomethingElse,TObject(MyDA[i].SortOrder));
end;
Note the trick of casting the Integer SortOrder into a TObject pointer, which is stored in the TStringList.Object property. (This depends upon the fact that Integer and Pointer are the same size.) Somewhere we must define a function to compare the TObject pointers:
function CompareObjects(ts:tStringList; Item1,Item2: integer): Integer;
begin
Result := CompareValue(Integer(ts.Objects[Item1]), Integer(ts.Objects[Item2]))
end;
Now, we can sort the tsList on .Object by calling .CustomSort instead of .Sort (which would sort on the string value.)
tsExamples.CustomSort(#CompareObjects); //Sort the list
The TStringList is now sorted, so you can iterate over it from 0 to .Count-1 and read the strings in sorted order.
But suppose you didn't want a TStringList, just an array in sorted order. Or the records contain more data than just the one string in this example, and your sort order is more complex. You can skip the step of adding every string, and just add the array index as Items in a TList. Do everything above the same way, except use a TList instead of TStringList:
var Mlist: TList; //a list of Pointers
...
for i:=0 to High(MyDA) do
Mlist.add(Pointer(i)); //cast the array index as a Pointer
Mlist.Sort(#CompareRecords); //using the compare function below
function CompareRecords(Item1, Item2: Integer): Integer;
var i,j: integer;
begin
i := integer(item1); //recover the index into MyDA
j := integer(item2); // and use it to access any field
Result := SomeFunctionOf(MyDA[i].SomeField) - SomeFunctionOf(MyDA[j].SomeField);
end;
Now that Mlist is sorted, use it as a lookup table to access the array in sorted order:
for i:=0 to Mlist.Count-1 do begin
Something := MyDA[integer(Mlist[i])].SomeField;
end;
As i iterates over the TList, we get back the array indexes in sorted order. We just need to cast them back to integers, since the TList thinks they're pointers.
I like doing it this way, but you could also put real pointers to array elements in the TList by adding the Address of the array element instead of it's index. Then to use them you would cast them as pointers to TExample records. This is what Barry Kelly and CoolMagic said to do in their answers.
If your need sorted by string then use sorted TStringList and
add record by TString.AddObject(string, Pointer(int_val)).
But If need sort by integer field and string - use TObjectList and after adding all records call TObjectList.Sort with necessary sorted functions as parameter.
This all depends on the number of records you are sorting. If you are only sorting less than a few hundred then the other sort methods work fine, if you are going to be sorting more, then take a good look at the old trusty Turbo Power SysTools project. There is a very good sort algorithm included in the source. One that does a very good job sorting millions of records in a efficient manner.
If you are going to use the tStringList method of sorting a list of records, make sure that your integer is padded to the right before inserting it into the list. You can use the format('%.10d',[rec.sortorder]) to right align to 10 digits for example.
The quicksort algorithm is often used when fast sorting is required. Delphi is (Or was) using it for List.Sort for example.
Delphi List can be used to sort anything, but it is an heavyweight container, which is supposed to look like an array of pointers on structures. It is heavyweight even if we use tricks like Guy Gordon in this thread (Putting index or anything in place of pointers, or putting directly values if they are smaller than 32 bits): we need to construct a list and so on...
Consequently, an alternative to easily and fastly sort an array of struct might be to use qsort C runtime function from msvcrt.dll.
Here is a declaration that might be good (Warning: code portable on windows only).
type TComparatorFunction = function(lpItem1: Pointer; lpItem2: Pointer): Integer; cdecl;
procedure qsort(base: Pointer; num: Cardinal; size: Cardinal; lpComparatorFunction: TComparatorFunction) cdecl; external 'msvcrt.dll';
Full example here.
Notice that directly sorting the array of records can be slow if the records are big. In that case, sorting an array of pointer to the records can be faster (Somehow like List approach).
With an array, I'd use either quicksort or possibly heapsort, and just change the comparison to use TExample.SortOrder, the swap part is still going to just act on the array and swap pointers. If the array is very large then you may want a linked list structure if there's a lot of insertion and deletion.
C based routines, there are several here
http://www.yendor.com/programming/sort/
Another site, but has pascal source
http://www.dcc.uchile.cl/~rbaeza/handbook/sort_a.html
Use one of the sort alorithms propose by Wikipedia. The Swap function should swap array elements using a temporary variable of the same type as the array elements. Use a stable sort if you want entries with the same SortOrder integer value to stay in the order they were in the first place.
TStringList have efficient Sort Method.
If you want Sort use a TStringList object with Sorted property to True.
NOTE: For more speed, add objects in a not Sorted TStringList and at the end change the property to True.
NOTE: For sort by integer Field, convert to String.
NOTE: If there are duplicate values, this method not is Valid.
Regards.
If you have Delphi XE2 or newer, you can try:
var
someVar: array of TExample;
list: TList<TExample>;
sortedVar: array of TExample;
begin
list := TList<TExample>.Create(someVar);
try
list.Sort;
sortedVar := list.ToArray;
finally
list.Free;
end;
end;
I created a very simple example that works correctly if the sort field is a string.
Type
THuman = Class
Public
Name: String;
Age: Byte;
Constructor Create(Name: String; Age: Integer);
End;
Constructor THuman.Create(Name: String; Age: Integer);
Begin
Self.Name:= Name;
Self.Age:= Age;
End;
Procedure Test();
Var
Human: THuman;
Humans: Array Of THuman;
List: TStringList;
Begin
SetLength(Humans, 3);
Humans[0]:= THuman.Create('David', 41);
Humans[1]:= THuman.Create('Brian', 50);
Humans[2]:= THuman.Create('Alex', 20);
List:= TStringList.Create;
List.AddObject(Humans[0].Name, TObject(Humans[0]));
List.AddObject(Humans[1].Name, TObject(Humans[1]));
List.AddObject(Humans[2].Name, TObject(Humans[2]));
List.Sort;
Human:= THuman(List.Objects[0]);
Showmessage('The first person on the list is the human ' + Human.name + '!');
List.Free;
End;