Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2008-01

counting items in a set type

3 messages · 2 people ·

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Graeme Geldenhuys

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?

Regards,
- Graeme -

_______________________________________________
fpGUI - a cross-platform Free Pascal GUI toolkit
http://opensoft.homeip.net/fpgui/

Reply by email

Michael Van Canneyt
to Graeme Geldenhuys
Graeme Geldenhuys wrote 33 lines
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.

Reply by email

Graeme Geldenhuys
to Michael Van Canneyt
Michael Van Canneyt wrote 12 lines
> > for i := Low(TfpgMsgDlgBtn) to High(TfpgMsgDlgBtn) do > begin > if i in Buttons then > inc(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.

[ Wow, a quick response! ]

OK, thanks Michael. The for loop actually gives me time to extract the correct string (text) for each enum type at the same time, so it ends up being handy after all. I just wasn't sure if there was a different way to do it.

Regards,
- Graeme -

_______________________________________________
fpGUI - a cross-platform Free Pascal GUI toolkit
http://opensoft.homeip.net/fpgui/

Reply by email