[fpc-pascal] counting items in a set type

Michael Van Canneyt michael at freepascal.org
Thu Jan 10 14:46:59 CET 2008



On Thu, 10 Jan 2008, Graeme Geldenhuys wrote:

> Hi,
> 
> I momentarily forgot how to do this... It's late in the week. ;)
> 
> I have set items in a Set type.  How to I count how many items are in the set?
> 
> eg:
> 
> TfpgMsgDlgBtn = (mbNoButton, mbYes, mbNo, mbOK, mbCancel, mbAbort,
>    mbRetry, mbIgnore, mbAll, mbNoToAll, mbYesToAll, mbHelp, mbClose);
> TfpgMsgDlgButtons = set of TfpgMsgDlgBtn;
> 
> ....
> 
> var
>   Buttons: TfpgMsgDlgButtons;
> 
> ....
> 
>   Buttons := [mbRetry, mbIgnore];   // it can be any amount of items.
> 
> 
> How do I know how many items are in Buttons?
> 
> Yes I can do a....
> 
>  for i := Low(TfpgMsgDlgBtn) to High(TfpgMsgDlgBtn) do
>  begin
>     if i in Buttons then
>         int(counter);
>  end;
> 
> Is there a better/quicker way of doing this?

No. 
You can try casting to an integer and count all set bits, but that's
highly non-portable and will not work for all sets.

Michael.



More information about the fpc-pascal mailing list