8000 Set to array convertor function · fragglet/c-algorithms@661f364 · GitHub
[go: up one dir, main page]

Skip to content

Commit 661f364

Browse files
committed
Set to array convertor function
1 parent 5cd0190 commit 661f364

File tree

3 files changed

+72
-0
lines changed

3 files changed

+72
-0
lines changed

src/set.c

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,40 @@ int set_num_entries(Set *set)
373373
return set->entries;
374374
}
375375

376+
void **set_to_array(Set *set)
377+
{
378+
void **array;
379+
int array_counter;
380+
int i;
381+
SetEntry *rover;
382+
383+
/* Create an array to hold the set entries */
384+
385+
array = malloc(sizeof(void *) * set->entries);
386+
array_counter = 0;
387+
388+
/* Iterate over all entries in all chains */
389+
390+
for (i=0; i<set->entries; ++i) {
391+
392+
rover = set->table[i];
393+
394+
while (rover != NULL) {
395+
396+
/* Add this value to the array */
397+
398+
array[array_counter] = rover->data;
399+
++array_counter;
400+
401+
/* Advance to the next entry */
402+
403+
rover = rover->next;
404+
}
405+
}
406+
407+
return array;
408+
}
409+
376410
struct set_union_data {
377411
Set *new_set;
378412
SetCopyFunc copy_func;

src/set.h

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,15 @@ void set_foreach(Set *set, SetIterator callback, void *user_data);
187187

188188
int set_num_entries(Set *set);
189189

190+
/**
191+
* Create an array containing all entries in a set.
192+
*
193+
* @param set The set.
194+
* @return An array containing all entries in the set.
195+
*/
196+
197+
void **set_to_array(Set *set);
198+
190199
/**
191200
* Perform a union of two sets.
192201
*

test/test-set.c

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ POSSIBILITY OF SUCH DAMAGE.
4040
#include "set.h"
4141
#include "compare-int.h"
4242
#include "hash-int.h"
43+
#include "compare-pointer.h"
44+
#include "hash-pointer.h"
4345

4446
Set *generate_set(void)
45< FE57 /td>47
{
@@ -238,6 +240,33 @@ void test_set_intersection(void)
238240
}
239241
}
240242

243+
void test_set_to_array(void)
244+
{
245+
Set *set;
246+
int values[100];
247+
int **array;
248+
int i;
249+
250+
/* Create a set containing pointers to all entries in the "values"
251+
* array. */
252+
253+
set = set_new(pointer_hash, pointer_equal);
254+
255+
for (i=0; i<100; ++i) {
256+
values[i] = 1;
257+
set_insert(set, &values[i]);
258+
}
259+
260+
array = (int **) set_to_array(set);
261+
262+
/* Check the array */
263+
264+
for (i=0; i<100; ++i) {
265+
assert(*array[i] == 1);
266+
*array[i] = 0;
267+
}
268+
}
269+
241270
int main(int argc, char *argv[])
242271
{
243272
test_set_new();

0 commit comments

Comments
 (0)
0