SET ADT

D

dieymir

Anybody has any idea about how to define a mathematical set in C (like
the Pascal one SET ... OF ...) with operations like union,
intersection, pertenence ...

Thanks a lot.
 
B

Ben Pfaff

Anybody has any idea about how to define a mathematical set in C (like
the Pascal one SET ... OF ...) with operations like union,
intersection, pertenence ...

Normally this is done with a bitmap. You assign each member of
the set to a bit. Then union can be taken with the | operator,
intersection with &. I don't know what "pertenence" is.

Here's a worked example. Suppose you have a set of fruit that
might contain an apple, an orange, or a pear. Then give each of
those a bit:

#define APPLE (1u << 0)
#define ORANGE (1u << 1)
#define PEAR (1u << 2)

unsigned basket1 = APPLE; /* Just an apple. */
unsigned basket2 = ORANGE | PEAR; /* An orange and a pear. */
unsigned both_baskets = basket1 | basket2; /* Union. */

/* Is there an apple in basket2? */
if (basket2 & APPLE) { ... }

/* Remove an orange from basket2. */
basket2 &= ~ORANGE;

....etc...
 
D

dieymir

Ben Pfaff said:
intersection with &. I don't know what "pertenence" is.
I mean check if an element belongs to the set or not (Pascal/Modula-2 IN operator)
 
D

dieymir

Xenos said:
This is C++, but you can extract the logic and make a C interface. It
provide a Pascal-like set class.

Thanks a lot for the code. Actually I don't know C++, but I know Java
and some Objective-C (both have a Set ADT in their API :). I suppose
that C++ won't be much different of those.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,016
Latest member
TatianaCha

Latest Threads

Top