Sunday, July 12, 2009

How can i landing a set by c prog ramming?

structure datas

How can i landing a set by c prog ramming?
If you can work in C++, there are many set


implementations available in the standard template


library. However, if you're working in C, you


can add functional/useful sets using just a small number


of bitwise and logical operations.





The basic idea is that a set will be a bit vector,


and element "i" will be at position "1%26lt;%26lt;i".


For small sets (say, up to 32 or 64), you can


hold the sets in a scalar variable. For larger


sets, you'd need to create an array of scalars and factor


that into the accessing code.





With no error checking, and just for illustration,


I've included a trivial example of using "bit vector"


sets in C:





#include %26lt;stdio.h%26gt;





typedef long set_t;





#define clear_set(x) (x=0)


#define set_element(e, x) (x |= (1%26lt;%26lt;(e)))


#define is_element(e, x) ((1%26lt;%26lt;(e)) %26amp; x)


#define sizeof_set (sizeof(set_t)*8)





int


main()


{


int i;


set_t s;





clear_set(s);





set_element(5, s);


set_element(15, s);


set_element(25, s);





printf("The set consists of [");


for (i=0; i%26lt;sizeof_set; i++) {


if (is_element(i, s)) {


printf(" %d", i);


}


}


printf(" ]\n");


return 0;


}





When compiled and executed, it demonstrates that


it correctly created a set with elements 5, 15, and 25.





$ cc set.c


$ a.out


The set consists of [ 5 15 25 ]
Reply:If you're trying to define a set in C, use an enumeration with bitwise operations to determine which elements are in the set.





VALUE1 = 0x01;


VALUE2 = 0x02;


VALUE3 = 0x04;


VALUE4 = 0x08;





/* evaluation = is VALUE1 in set x? */


if (setx == setx AND VALUE1)


{


Do TRUE stuff


}


else


{


Do FALSE stuff


}





/* including element in set */


setx = setx OR VALUE1;





/* excluding element in set */


setx = setx XOR VALUE1;





Sorry if the syntax is not perfect...it's been awhile since I've used C.

garland flower

No comments:

Post a Comment