How to skip this loop?

This is a sorted list with 50,000 items (strings) in delphi. How to quickly search for elements with the same prefix words and then skip the loop?

The list is as follows:

aa..... ab cd//from here ab kk ab li ab mn ab xy// to here ac xz ... 

I mean, how to quickly find and copy elements with the prefixes ab and skip out loop. Suppose that the index of one of the elements ab is obtained in a binary search. The index ab cd in ab xy is obtained through a binary search.

Thank you very much.

Edit: We thank everyone for your answers.

+4
source share
2 answers

If you want something fast, do not store your data in TListView.

Use TStringList to store the list, then use TListView in virtual mode.

Reading from TStringList.Items [] is many times faster than reading from the TListView.Items [] property.

If you are sure that there is no void element in the list, the following is used:

 procedure Extract(List, Dest: TStrings; Char1, Char2: char); var i,j: integer; V: cardinal; type PC = {$ifdef UNICODE}PCardinal{$else}PWord{$endif}; begin V := ord(Char1)+ord(Char2) shl (8*sizeof(char)); Dest.BeginUpdate; Dest.Clear; for i := 0 to List.Count-1 do begin if PC(pointer(List[i]))^=V then begin for j := i to List.Count-1 do begin Dest.Add(List[j]); if PC(pointer(List[j]))^<>V then break; // end the for j := loop end; break; // end the for i := loop end; Dest.EndUpdate; end; 

You can use binary search to get it even faster. But with the PWord () trick in the list of 50,000 items, you won't notice it.

Note that PC (pointer (List [i])) ^ = V is a faster version of the copy (List [i], 1,2) = Char1 + Char2, because no time line is created during the comparison. But it only works if List [i] = '', that is, there is no pointer (List [i]) = nil.

I added {$ ifdef UNICODE} and sizeof (char) so that this code compiles with the whole version of Delphi (before and after Delphi 2009).

+6
source

To stop the loop, use the break command. Exit also useful to leave the whole function, especially when you have several nested loops to exit. As a last resort, you can use goto to jump out of several nested loops and continue working in the same function.

If you use a while or repeat instead of a for loop, you can include another conjunctive in the stop condition that you set in the middle of the loop:

 i := 0; found := False; while (i < count) and not found do begin // search for items found := True; // more stuff Inc(i); end; 
+4
source

All Articles